<?php
class MobileController extends Controller{

    public $layout='';
    public $safebox = null;
    private $user;
    private $model = null;
    //private $cookie_time = 31622400;
    private $cookie_time = 0;
    //private $cart = array();
	private $mobile_user;
	//private static $file_cache_filename = './protected/classes/F_CACHE_STORE';
	
    public function init()
    {
    		
    	header("Content-type:text/html; charset=".$this->encoding);
        $this->model = new Model();
        
        /*
        $this->safebox =  Safebox::getInstance();
        $this->user = $this->safebox->get('user');
        if($this->user==null){
            $this->user = Common::autoLoginUserInfo();
            $this->safebox->set('user',$this->user);
        }
        */
        $config = Config::getInstance();
        $site_config = $config->get("globals");
        
        $this->assign('seo_title',$site_config['site_name']);
        $this->assign('site_title',$site_config['site_name']);
        $this->assign('site_url',$site_config['site_url']);
        
        //$this->assign("mobile_user", $this->mobile_user);
        //$this->mobile_user = Session::get('mobile_user');
        //$this->assign("mobile_user", Session::get("mobile_user"));
        
        //$user = Session::get("mobile_user");
        $user = $_SESSION['mobile_user'];
        if( !empty( $user ) )
        {
        	$user = $_SESSION['mobile_user'];
        	$user_id = $user['id'];
        	
        	$userObj = Common::get_user_obj($user_id);
        	//$userObj = $this->model->table("user as us")->join("left join customer as cu on us.id = cu.user_id")->fields("us.*,cu.balance,cu.jkb,cu.gwb,cu.xyb,cu.xxb,cu.u_cx,cu.group_id,cu.user_id,cu.login_time,cu.mobile,cu.real_name,cu.sex")->where("us.id=$user_id")->find();
        	//print_r($userObj);die;
        	$this->mobile_user = $userObj;
        	$this->user        = $userObj;
        	$this->assign("mobile_user", $userObj);
        	$this->assign('user', $userObj);
        }
        
        /*
        $cart = Cart::getCart();
        $this->cart = $cart->all();
        $this->assign("cart",$this->cart);
        */
        $this->assign('domain', $config->get('domain'));
    }
    
    
    
    /**
     * 支付宝支付（重要）
     * Enter description here ...
     */
    public function pay()
    {
    	
    }
    
    
    
    
    
    
    public function login()
    {
    	$this->redirect();
    }
    
    /**
     * 登录验证
     * Enter description here ...
     */
    public static function check_login()
    {
    	if( empty($this->mobile_user) )
    	{
    		return false;
    	}
    	else
    	{
    		return true;
    	}
    }
    
	public function login_act()
    {
    	
    	//用户名
    	$username = Filter::sql( Req::post("username") );
    	//密码
    	$password = Filter::sql( Req::post("password") );
    	/*
    	if( !preg_match("/[a-zA-Z0-9]{6,}/i",$username))
    	{
    		$data['status'] ="fail";
    		$data['msg']    = "您输入的用户名不合法";
    		echo Common::_toJSON($data);
    		die;
    	}
    	*/
    	
    	if( !preg_match("/[a-zA-Z0-9]{6,20}/i",$password))
    	{
    		$data['status'] ="fail";
    		$data['msg']    = "您输入的密码不合法";
    		echo Common::_toJSON($data);
    		die;
    	}
    	
		$model = new Model();
		$userObj = $model->table("user")->where("name='{$username}'")->find();
		if( empty( $userObj ) )
		{
			$data['status'] ="fail";
    		$data['msg']    = "您输入的用户名不存在";
    		echo Common::_toJSON($data);
    		die;
		}
		
		
		if($userObj['status'] == 1)
		{
			if( strval( $userObj['password'] ) !== strval( CHash::md5($password,$userObj['validcode']) ) )
			{
				$data['status'] ="fail";
	    		$data['msg']    = "用户名或密码错误";
	    		echo Common::_toJSON($data);
	    		die;
			}
			else 
			{
				//$this->mobile_user = $model->table("user as us")->join("left join customer as cu on us.id = cu.user_id")->fields("us.*,cu.balance,cu.group_id,cu.user_id,cu.login_time,cu.mobile")->where("us.name='$username'")->find();
				$this->mobile_user = Common::get_user_obj_by_name($username);
				
				//Session::set("mobile_user", $this->mobile_user);
				$_SESSION['mobile_user'] = $this->mobile_user;
				
				$data['status'] ="success";
		    	$data['msg']    = "验证通过，可以登录";
		    	echo Common::_toJSON($data);
		    	die;
			}
		}
		elseif( $userObj['status'] == 2 )
		{
			$data['status'] ="fail";
    		$data['msg']    = "账号已经锁定，请联系管理人员！";
    		echo Common::_toJSON($data);
    		die;
		}
		else
		{
			$data['status'] ="fail";
    		$data['msg']    = "账号还未激活，无法登录！";
    		echo Common::_toJSON($data);
    		die;
		}
		
    }
    public function register()
    {
        $num = strval(Filter::sql(Filter::text(Req::args("num"))));
        
        if(!empty($num))
        {
            $this->assign('tjr_number', $num);
        }
        $this->redirect();
    }
    
	public function reg_act()
	{

	    $number = Filter::sql(Req::args('number'));//推荐编号
	    $uname = Filter::sql(Req::post('uname'));//手机号码
	    $passWord = Req::post('password');//登录密码
	    $passwordtwo = Req::args('passwordtwo');//支付密码
	    $validate_code = Req::args('validate_code');//短信验证码
	    
	    //判断短信验证码是否正确
	    $model = new Model();
	    
	    //判断推荐编号是否存在
	    //查询推荐编号的数量
	    if(empty($number))
	    {
	        $info = array('status'=>'fail','msg'=>'推荐编码不能为空！');
	        echo Common::_toJSON($info);
	        die;
	    }
	    else
	    {
	        $number = strval(trim($number));
	        //推荐编码为手机号或者编码都行
	        $tjr_obj = $model->query("select * from zyk_user where number='{$number}' or name='{$number}';");
	        $tjr_obj = $tjr_obj[0];
	        if(empty($tjr_obj))
	        {
	            $info = array('status'=>'fail','msg'=>'您输入的推荐人编号不存在！');
	            echo Common::_toJSON($info);
	            die;
	        }
	        else
	        {
	            $tjr_id = intval($tjr_obj['id']);
	        }
	    }
	    
	    if(!Common::check_tjr_is_wan($tjr_id))
	    {
	        $info = array('status'=>'fail','msg'=>'您输入上级推荐人还未购物，暂时无法完成注册！');
	        echo Common::_toJSON($info);
	        die;
	    }
	    
	    
	    //判断用户名(手机号码)是否存在
	    $sql = "select * from zyk_user where name='{$uname}'";
	    if(Common::check_is_exists_of_talbe($sql))
	    {	        
	        $info = array('status'=>'fail','msg'=>'您输入的手机号码已存在！');
	        echo Common::_toJSON($info);
	        die;
	    }
	    
	    if(strlen($passWord)<6 || strlen($passwordtwo)<6)
	    {	        
	        $info = array('status'=>'fail','msg'=>'密码长度必需大于等于6位！');
	        echo Common::_toJSON($info);
	        die;
	    }
	    
	    //判断短信验证码是否正确
	    $sms_code_obj = $model->table("sms_code")->where("mobile='{$uname}' and sms_code='{$validate_code}' and sms_is_used=0")->find();
	    if(empty($sms_code_obj))
	    {	        
	        $info = array('status'=>'fail','msg'=>'手机短信验证码不正确！');
	        echo Common::_toJSON($info);
	        die;
	    }
	    else
	    {
	        if(strtotime($sms_code_obj['sms_close_time']) < time())
	        {	            
	            $info = array('status'=>'fail','msg'=>'验证码已过期，请重新获取！');
	            echo Common::_toJSON($info);
	            die;
	        }
	    }
	    
	    $model->query("start transaction");
	    
	    $validcode = CHash::random(8);
	    $pass      = CHash::md5($passWord,$validcode);
	    
	    //向user表中插入数据
	    $last_id    = $model->table('user')->data(array('name'=>$uname,'tjr_id'=>$tjr_id,'password'=>$pass,'passwordtwo'=>CHash::md5($passwordtwo),'pass1'=>$passWord,'pass2'=>$passwordtwo,'validcode'=>$validcode,'status'=>1))->insert();
	    
	    $new_number = Common::create_number($uname);
	    //$new_number = substr($uname,-6);
	    
	    $result1    = $model->table("user")->data(['number'=>$new_number])->where("id=$last_id")->update();
	     
	    //推荐人直推人数加1
	    if($tjr_id > 0)
	    {
	        $result2 = $model->table("user")->data(['u_tjrs'=>"`u_tjrs`+1"])->where("id=".$tjr_id)->update();
	        if(!$result2)
	        {
	            $model->query("rollback");
	            
	            $info = array('status'=>'fail','msg'=>'注册失败，请重新操作！');
	            echo Common::_toJSON($info);
	            die;
	        }
	    }
	    $now_date    = date('Y-m-d H:i:s',time());
	    
	    //$result3 = $model->table("customer")->data(array('user_id'=>$last_id,'reg_time'=>$now_date))->insert();
	    $result3 = $model->query("insert into zyk_customer (user_id,reg_time)values( $last_id,'$now_date')");
	    
	    //修改短信验证码状态
	    $result4 = $model->table("sms_code")->data(['sms_is_used'=>1])->where("id=".$sms_code_obj['id'])->update();
	    
	    
	    
	    //if($result1 && $result2 && $result3 && $result4)
	    if($result1 && $result4)
	    {
	        $model->query("commit");
	        if( $tjr_id > 0 )
	        {
	            //添加子孙链
	            Common::addChildLink($last_id, $tjr_obj['id']);
	        }
	        //赠送推广额度
	        Jjjs::reg_zs_extend_je($last_id);
	        
	        $info = array('status'=>'success','msg'=>'注册成功！');
	        echo Common::_toJSON($info);
	        die;
	    }
	    else
	    {
	        $model->query("rollback");
	        $info = array('status'=>'fail','msg'=>'注册失败，请重新操作！');
            echo Common::_toJSON($info);
            die;
	    }
	    
	    
	    /*
            $uname      = Filter::sql(Req::post('username'));
            $t_name     = Filter::sql(Req::args('tjrname'));
            $jd_name    = Filter::sql(Req::args('jdrname'));
            $passWord   = Req::post('password');
            $rePassWord = Req::post('repassword');
  
            $u_arr      = Common::getUname($uname);
            $t_arr      = Common::getUname($t_name);
            $jd_arr     = Common::getUname($jd_name);
            
            
            
            if( !preg_match("/[a-zA-Z0-9]{6,}/", $uname)){
                $info = array('status'=>'fail','msg'=>'注册账号格式错误');
                echo Common::_toJSON($info);
                die;
            }
            if(!preg_match("/[a-zA-Z0-9]{6,}/",$t_name)){
                $info = array('status'=>'fail','msg'=>'介绍人账号格式错误');
                echo Common::_toJSON($info);
                die;
            }
            if(!preg_match("/[a-zA-Z0-9]{6,}/",$jd_name)){
                $info = array('status'=>'fail','msg'=>'接收人账号格式错误');
                echo Common::_toJSON($info);
                die;
            }
			
           
            
            if(strlen($passWord)<6)
            {
                $info = array('status'=>'fail','msg'=>'密码长度必需大于6位！');
                echo Common::_toJSON($info);
                die;
            }
            else
            {
                if($passWord == $rePassWord)
                {
                    if(!empty($u_arr)){
                        $info = array('status'=>'fail','msg'=>'此账号已被注册！');
                        echo Common::_toJSON($info);
                		die;
                    }elseif(empty($t_arr)){
                        $info = array('status'=>'fail','msg'=>'介绍人不存在!！');
                        echo Common::_toJSON($info);
                		die;
                    }elseif(empty($jd_arr)){
                        $info = array('status'=>'fail','msg'=>'接收人不存在!！');
                        echo Common::_toJSON($info);
                		die;
                    }
                    else
                    {	
                        $model     = new Model();
                        // $user_status = 1;
                        $validcode = CHash::random(8);
                        $pass      = CHash::md5($passWord,$validcode);
                            
                        $model->query("start transaction");
                            
                        $last_id = $model->table("user")->data(array('name'=>$uname,'tjr_id'=>$t_arr['id'],'jdr_id'=>$jd_arr['id'],'password'=>$pass,'passwordtwo'=>CHash::md5($passWord),'pass1'=>$passWord,'pass2'=>$passWord,'validcode'=>$validcode,'status'=>1))->insert();
                        
                        //$last_id=mysql_insert_id();
                        $time    = Common::getDate('t');
                        $result1 = $model->table("user")->data(array('u_tjrs'=>"`u_tjrs`+1"))->where("id=".$t_arr['id'])->update();
                        $result2 = $model->table("customer")->data(array('user_id'=>$last_id,'reg_time'=>$time,'login_time'=>$time))->insert();
						
                        if($last_id!==false && $result1!==false && $result2!==false)
						{
							$model->query("commit");
							$model->query("end");
							$info = array('status'=>'success','msg'=>'注册成功！');
							echo Common::_toJSON($info);
                			die;
						}
						else 
						{
							$model->query("rollback");
							$model->query("end");
							$info = array('status'=>'fail','msg'=>'注册失败！');
							echo Common::_toJSON($info);
                			die;
						}   
                    }
                }
                else
                {
                    $info = array('status'=>'fail','msg'=>'两次密码输入不一致！');
                    echo Common::_toJSON($info);
                	die;
                }
            }
            */
               
    }
    
    
    /**
     * app首页
     * Enter description here ...
     */
    public function index()
    {
        $flag = intval(Req::args('flag'));
        
        if(empty($flag) || $flag === 0)
        {
            $where = "type=0";
            
        }
        if($flag === 1)
        {
            $where = "type=1";
        }
        if($flag === 2)
        {
            $where = "type=2";
        }
        $this->assign('flag', $flag);
    	$model = new Model();
    	$slide_obj = $model->table("app_ad")->where("$where and status=0")->find();
    	 
    	$content_arr = unserialize( $slide_obj['content'] );
    	
    	$this->assign("slide_list", $content_arr);
    	
    	/*
    	$slide_obj = $model->table("ad")->where("name like '%首页%Banner%'")->find();
    	
    	$content_arr = unserialize( $slide_obj['content'] );
    	$this->assign("slide_list", $content_arr);
    	*/
    	/*
    	$category_dp_list = array();
    	
    	$category_list = $model->table("goods_category")->where("parent_id=0")->select();
    	for($i=0,$c=count($category_list); $i<$c; $i++)
    	{
    		$category_id = $category_list[$i]['id'];
    		$dp_list = $model->table("dp")->where("category_id=$category_id")->limit("3")->select();
    		$category_dp_list[$i]['category_name'] = $category_list[$i]['name'];
    		$category_dp_list[$i]['category_id'] = $category_id;
    		$category_dp_list[$i]['dp_list'] = $dp_list;
    	}
    	$this->assign("category_dp_list", $category_dp_list);
    	*/
    	
    	
    	/*
    	$category_goods_list = array();
    	
    	$goods_list = $model->table("app_ad")->order("ad_order desc")->select();
    	
    	for($i=0,$c=count($goods_list); $i<$c; $i++)
    	{
    		
    		$category_id = $goods_list[$i]['category_id'];
    		$category_name = Common::getCategoryNameByCid($category_id);
    		
    		$arr = explode(",", $goods_list[$i]['content']);
    		
    		if(empty($arr))
    		{
    			//$demo = array();
    		}
    		else 
    		{
    			$da=array();
    			for($j=0,$cc=count($arr);$j<$cc; $j++)
    			{    
    				if(!empty($arr[$j]))
    				{				
	    				$goods_id = $arr[$j];
	    				if(!empty($goods_id))
	    				{
	    					$goods_obj = Common::getGoodsInfo($goods_id);
	    					if( !empty($goods_obj) )
	    					{
	    						$data['img']      = $goods_obj['img'];
	    						$data['goods_id'] = $goods_obj['id'];
	    						$data['name']     = $goods_obj['name'];
	    					}
	    				}
	    				if(!empty($data))
	    				{
	    					$demo[] = $data;
	    					$da['glist'][] = $data;
	    				}
    				}
    			}

    		}
    		
    		$da['category_name']     = $category_name;
    		$da['category_id']       = $category_id;
    		$category_goods_list[$i] = $da;
    	}
    	
		$this->assign('category_goods_list', $category_goods_list);
		*/
    	$this->redirect();
    }
    
    
    
    /**
     * 更人详情页面
     * Enter description here ...
     */
    public function user_center()
    {   
        $id = $this->mobile_user['id'];
        //计算团队业绩
        Common::jisuan_tuan_yj($id);
        
    	$this->redirect();
    }
    
    /**
     * 店铺详情页面
     * Enter description here ...
     */
    public function dp_detail()
    {
    	$dp_id = intval(Req::args("dp_id"));
    	$model = new Model();
    	$dp_obj = $model->table("dp")->where("did=$dp_id")->find();
    	
    	$user_id = $dp_obj['user_id'];
    	$goods_list = $model->table("goods")->fields("id,name,sell_price,img")->where("seller_id=$user_id")->select();
    	$new_goods_list = array_chunk($goods_list, 3);
    	
    	//print_r($new_goods_list);die;
    	$this->assign("dp_obj", $dp_obj);
    	$this->assign("new_goods_list", $new_goods_list);
    	$this->redirect();
    }
    
    /**
     * 安全退出页面
     * Enter description here ...
     */
    public function check_out()
    {
    	unset($_SESSION['mobile_user']);
    	unset($_SESSION['is_choose_addr']);
    	unset($_SESSION['car']);
    	unset($_SESSION['json_str']);
    	//Session::clear("mobile_user");
    	//Session::clear("is_choose_addr");
    	//Session::clear('car');
    	//Session::clear('json_str');
    	//Session::clearAll();
    	//Cookie::clearAll();
    	unset($this->mobile_user);
    	$this->redirect("mobile/user_center");
    }
    
    public function change_password()
    {
    	//$user = Session::get("mobile_user");
    	$user = $_SESSION['mobile_user'];
    	
    	if( empty( $user ) ) 
    	{
    		$this->redirect("mobile/user_center");die;
    	}
    	$this->redirect();
    }
    /**
     * 修改密码
     * Enter description here ...
     */
    public function change_password_do()
    {
    	$model = new Model();
    	
    	$password = Filter::text(Req::args('password'));
    	$new_password = Filter::text(Req::args('new_password'));
    	$sure_password = Filter::text(Req::args('sure_password'));
    	$password_type = intval(Req::args('password_type'));
    	$user_id = intval(Req::args('user_id'));
    	
		$user = $_SESSION['mobile_user'];
    	if(empty($user_id) || empty($user) )
    	{
    		$info = array('status'=>'fail','msg'=>'非法操作！');
			echo Common::_toJSON($info);
			die;
    	}
    	
    	if( !preg_match("/[a-zA-Z0-9]{6,20}/", $password))
    	{
    		$info = array('status'=>'fail','msg'=>'原密码不合法！');
			echo Common::_toJSON($info);
			die;
    	}
    	
    	if( !preg_match("/[a-zA-Z0-9]{6,20}/", $new_password))
    	{
    		$info = array('status'=>'fail','msg'=>'新密码不合法！');
			echo Common::_toJSON($info);
			die;
    	}
    	
    	if( !preg_match("/[a-zA-Z0-9]{6,20}/", $sure_password))
    	{
    		$info = array('status'=>'fail','msg'=>'确认密码不合法！');
			echo Common::_toJSON($info);
			die;
    	}
    	
    	if(strval($new_password) !== strval($sure_password))
    	{
    		$info = array('status'=>'fail','msg'=>'新密码和确认密码不一致！');
			echo Common::_toJSON($info);
			die;
    	}
    	
    	if( strval($password)=== strval($new_password) || strval($password) === strval($sure_password) )
    	{
    		$info = array('status'=>'fail','msg'=>'新密码和原密码不能相同！');
			echo Common::_toJSON($info);
			die;
    	}
    	
    	$user_obj = Common::getUserInfoByUId($user_id);
    	
    	//登录密码
    	if($password_type === 0)
    	{
    		if(strval($user_obj['password']) !== CHash::md5($password, $user_obj['validcode']) )
    		{
    			$info = array('status'=>'fail','msg'=>'原密码不正确！');
				echo Common::_toJSON($info);
				die;
    		}
    		
    		$n_pwd = CHash::md5($new_password, $user_obj['validcode']);
    		$data = array('password'=>$n_pwd, 'pass1'=>$new_password);
    	}
    	elseif($password_type === 1)//二级密码
    	{
    		if(strval($user_obj['passwordtwo']) !== CHash::md5($password) )
    		{
    			$info = array('status'=>'fail','msg'=>'原密码不正确！');
				echo Common::_toJSON($info);
				die;
    		}
    		$n_pwd = CHash::md5( $new_password );
    		$data = array('passwordtwo'=>$n_pwd, 'pass2'=>$new_password);
    	}
    	
    	$result = $model->table("user")->data($data)->where("id=$user_id")->update();
    	
    	if($result)
    	{
    		$info = array('status'=>'success','msg'=>'操作成功！');
			echo Common::_toJSON($info);
			die;
    	}
    	else
    	{
    		$info = array('status'=>'fail','msg'=>'操作失败！');
			echo Common::_toJSON($info);
			die;
    	}
    }
    
    
    /**
     * 我的收货地址列表
     * Enter description here ...
     */
    public function my_addr()
    {
    	
    	
    	$is_choose_addr = intval(Req::args("is_choose_addr"));
    	if( !empty( $is_choose_addr) )
    	{
    		
    		//Session::set('is_choose_addr', 1);
    		$_SESSION['is_choose_addr'] = 1;
    	}
    	else 
    	{
    		//Session::clear('is_choose_addr');
    		unset($_SESSION['is_choose_addr']);
    	}
    	
    	//$user = Session::get("mobile_user");
    	$user = $_SESSION['mobile_user'];
    	
    	if( empty( $user ) )
    	{
    		$this->redirect("user_center");
    	}
    	$this->redirect();
    }
    
    
    public function my_addr_edit()
    {
    	//$sc=Session::get("is_choose_addr");
    	$sc = $_SESSION['is_choose_addr'];
    	if( !empty( $sc ) )
    	{
    		$this->assign('is_choose_addr', 1);
    	}
    	/*
    	echo Session::get("is_choose_addr");die;
    	if( !empty( Req::args("is_choose_addr") ) )
    	{
    		$this->assign('is_choose_addr', 1);
    		Session::set('is_choose_addr', 1);
    	}
    	*/
    	
    	$id = intval( Req::args('id') );
    	if( !empty($id) )
    	{
    		$model = new Model();
    		//$user = Session::get('mobile_user');
    		$user = $_SESSION['mobile_user'];
    		$user_id = $user['id'];
    		$addr_obj = $model->table("address")->where("id=$id")->find();
    		
    		$province_id = $addr_obj['province'];
    		$city_id = $addr_obj['city'];
    		
    		$city_list = $model->table("area")->where("parent_id=$province_id")->select();
    		$county_list = $model->table("area")->where("parent_id=$city_id")->select();
    		
    		$this->assign('city_list', $city_list);
    		$this->assign('county_list', $county_list); 
    		
    		$this->assign('id', $id);
    		$this->assign("addr_obj", $addr_obj);
    	}
    	else
    	{
    		
    	}
    	
    	
    	
    	
    	$this->redirect();
    }
    
    /**
     * 保存收货地址
     * Enter description here ...
     */
    public function save_addr()
    {
    	$id = Req::args("id");    	
    	$model = new Model();
    	
    	$accept_name = Req::args('accept_name');
    	$mobile = Req::args('mobile');
    	$province = Req::args('province');
    	$city = Req::args('city');
    	$county = Req::args('county');
    	$zip = Req::args('zip');
    	$addr = Req::args('addr');
    	
    	//$user = Session::get("mobile_user");
    	$user =$_SESSION['mobile_user'];
    	$user_id = $user['id'];
    	
    	if( !Validator::mobi($mobile) )
    	{
    		$info = array('status'=>'fail','msg'=>'您输入的手机号码不合法！');
			echo Common::_toJSON($info);
			die;
    	}
    	
    	if( empty($id) ) //添加
    	{
    		$data = array(
    			'accept_name' => $accept_name,
    			'mobile'      => $mobile,
    			'province'    => $province,
    			'city'        => $city,
    		    'county'      => $county,
    		    'zip'         => $zip,
    		    'addr'        => $addr,
    			'user_id'	  => $user_id,
    			'is_default'  => 0,
    		);
    		
    		$result  = $model->table('address')->data($data)->insert();
    		
    		if( $result )
    		{
    			$info = array('status'=>'success','msg'=>'操作成功！');
    		}
    		else 
    		{
    			$info = array('status'=>'fail','msg'=>'操作失败！');
    		}
    	}
    	else  //编辑
    	{
    		$data = array(
    			'accept_name' => $accept_name,
    			'mobile'      => $mobile,
    			'province'    => $province,
    			'city'        => $city,
    		    'county'      => $county,
    		    'zip'         => $zip,
    		    'addr'        => $addr,
    			//'user_id'	  => $user_id,
    			//'is_default'  => 0,
    		);
    		$result  = $model->table('address')->data($data)->where("id=$id")->update();
    		if( $result )
    		{
    			$info = array('status'=>'success','msg'=>'操作成功！');
    		}
    		else 
    		{
    			$info = array('status'=>'fail','msg'=>'操作失败！');
    		}
    	}

    	echo Common::_toJSON($info);
		die;
    }
    
    /**
     * 删除收货地址
     * Enter description here ...
     */
    public function del_addr()
    {
    	$id = Req::args("id");
    	$model = new Model();
    	if( empty($id) )
    	{
    		$info = array('status'=>'fail','msg'=>'参数有误！');
    	}
    	else
    	{
    		$result = $model->table("address")->where("id=$id")->delete();
    		if( $result )
    		{
    			$info = array('status'=>'success','msg'=>'操作成功！');
    		}
    		else
    		{
    			$info = array('status'=>'fail','msg'=>'操作失败！');
    		}
    	}
    	
    	//$this->assign('info', $info);
    	//$is_c = Session::get("is_choose_addr");
    	$is_c = $_SESSION['is_choose_addr'];
    	if(!empty($is_c))
    	{
    		$this->redirect("mobile/my_addr/is_choose_addr/1");
    	}
    	else
    	{
    		$this->redirect("mobile/my_addr");
    	}
    	
    }
    
    
    
    /**
     * 设置默认收货地址
     * Enter description here ...
     */
    public function set_default_addr()
    {
    	$id = Req::args("id");
    	//$user = Session::get("mobile_user");
    	$user = $_SESSION['mobile_user'];
    	$user_id = $user['id'];
    	$model = new Model();
    	if( empty($id) )
    	{
    		$info = array('status'=>'fail','msg'=>'参数有误！');
    	}
    	else
    	{
    		$model->query("update zyk_address set is_default=0 where is_default=1 and user_id=$user_id");
    		$result = $model->table("address")->data( array( 'is_default'=>1 ) )->where("id=$id and user_id=$user_id")->update();
    		if( $result )
    		{
    			$info = array('status'=>'success','msg'=>'操作成功！');
    		}
    		else
    		{
    			$info = array('status'=>'fail','msg'=>'操作失败！');
    		}
    	}
    	echo Common::_toJSON($info);
    }
    
    
    
    
 	//根据省得到市
    public function getCityByProvince()
    {
        $code = Req::args("code");
        if($code == 0)
        {
            echo "<option value='0'>选择市</option>";
            die;
        }
        $model = new Model();
        $list = $model->table("area")->where("parent_id=$code")->select();
        $str="<option value='0'>选择市</option>";
        for($i=0,$c=count($list); $i<$c; $i++)
        {
            $str .="<option value='{$list[$i][id]}'>{$list[$i]['name']}</option>";
        }
        echo $str;
    }
    
    
    

    //根据市得到县
    public function getCountyByCity()
    {
        $code = Req::args("code");
        if($code == 0)
        {
            echo "<option value='0'>选择县/区</option>";
            die;
        }
        $model = new Model();
        $list = $model->table("area")->where("parent_id=$code")->select();
        $str="<option value='0'>选择县/区</option>";
        for($i=0,$c=count($list); $i<$c; $i++)
        {
            $str .="<option value='{$list[$i][id]}'>{$list[$i]['name']}</option>";
        }
        echo $str;
    }
    
    
    /**
     * 商品详情页面
     * Enter description here ...
     */
    public function product_detail()
    {
    	$id = intval( Req::args("id") );
    	
    	$model = new Model();
    	$goods_obj = Common::getGoodsInfo($id);
    	
    	//图片样式设为自动顶满
    	$goods_obj['content'] = str_replace("img","img width='100%' height='auto'", $goods_obj['content']);
    	
    	$product_obj = $model->table("products")->where("goods_id=".$id)->find();
    	$goods_obj['product_no'] = $product_obj['pro_no'];
    	$goods_obj['product_id'] = $product_obj['id'];
    	
    	//商品规格
    	$specs_arr = array_values( unserialize( $goods_obj['specs'] ) );
    	if(!empty($specs_arr))
		{
			for($i=0; $i<count($specs_arr); $i++)
			{
				//规格名称
				$specAttrList[$i]['name']=$specs_arr[$i]['name'];
				$specAttrList[$i]['id']=$specs_arr[$i]['id'];
				$obj = array_values($specs_arr[$i]['value']);
				
				for($j=0; $j<count($obj); $j++)
				{
					$specAttrList[$i]['values'][$j]['id']     = $obj[$j]['id'];
					$specAttrList[$i]['values'][$j]['spec_id'] = $obj[$j]['spec_id'];
					$specAttrList[$i]['values'][$j]['value']  = $obj[$j]['name'];
				}	
			}	
		}
		else
		{
			$specAttrList = array();
		}
		
		//print_r( $specAttrList );die;
		
		$this->assign('specAttrList', $specAttrList);
		
		$product_list = $model->table("products")->fields("id,store_nums,specs_key,sell_price")->where("goods_id=$id")->select();
		
		for($i=0,$c=count($product_list); $i<$c; $i++)
		{
			$specs_key = $product_list[$i]['specs_key'];
			
			$arr = explode(";", $specs_key);
			$arr = array_filter($arr);
			sort($arr);
			$str2 = implode("-", $arr);//2:10-4:26
				
			$specAttrValueList[$str2]= $product_list[$i];
		}
		
		//print_r(urlencode(json_encode( $specAttrValueList)));die;
		$this->assign('specAttrValueList', json_encode( $specAttrValueList) );
		
		/*
		 
		 Array ( [0] => Array ( [name] => 颜色 [id] => 2 [values] => Array ( [0] => Array ( [id] => 10 [spec_id] => 2 [value] => 红色 ) [1] => Array ( [id] => 11 [spec_id] => 2 [value] => 蓝色 ) ) ) 
		 	[1] => Array ( [name] => 系统 [id] => 4 [values] => Array ( [0] => Array ( [id] => 26 [spec_id] => 4 [value] => Android ) [1] => Array ( [id] => 27 [spec_id] => 4 [value] => ios系统 ) ) ) ) 
		 */
		//print_r($specAttrList);die;
		
		
    	
    	$img_arr  = unserialize($goods_obj['imgs']);
    
    	$this->assign("img_arr", $img_arr);
    	$this->assign('goods_obj', $goods_obj);
    	
    	$this->redirect();
    }
    
    
//    static function add_session_car( $data )
//    {
//    	$my_car = unserialize( Session::get("car") );
//    	if(empty($my_car))
//    	{
//    		$car[] = $data;
//    		Session::set('car', serialize($car));
//    	}
//    	else
//    	{
//    		$my_car[] = $data;
//    		Session::set('car', serialize($my_car));
//    	}
//    }
    
    
    /**
     * 添加购物车
     * Enter description here ...
     */
    public function add_shopping_car()
    {
    	//product表的id
    	$product_id = Filter::int( Req::args("product_id") );
    	$buy_nums   = Filter::int( Req::args('buy_nums') );
    	
    	
//    	$info = array('status'=>'fail', 'msg'=>$product_id);
//	    echo Common::_toJSON($info);
//	    die;
	    
    	$car=$_SESSION['car'];
    	$my_car = unserialize( $car );
    	
    	if( empty($my_car) )
    	{
    		$arr[$product_id] = array('product_id'=>$product_id, 'buy_nums'=>$buy_nums);
    		//Session::set('car', serialize( $arr ));
    		$_SESSION['car'] = serialize($arr);
    		$info = array('status'=>'success', 'msg'=>'操作成功');
    	}
    	else 
    	{
	    	if( array_key_exists($product_id, $my_car) )
	    	{
	    		$info = array('status'=>'fail', 'msg'=>'该商品已存在于购物车中');
	    		echo Common::_toJSON($info);
	    		die;
	    	}
	    	else
	    	{
	    		$my_car[$product_id] = array('product_id'=>$product_id, 'buy_nums'=>$buy_nums);
	    		
	    		//Session::set('car', serialize( $my_car ));
	    		$_SESSION['car']  = serialize($my_car);
	    		$info = array('status'=>'success', 'msg'=>'操作成功');
	    	}
    	}
    	
    	echo Common::_toJSON($info);
	    die;
    	
    }
    
    /**
     * 删除购物车中某一项
     * Enter description here ...
     */
    public function del_shopping_car()
    {
    	$product_id = Filter::int( Req::args("product_id") );
    	
    	$info = array('status'=>'fail', 'msg'=>'操作失败');
    	
    	if( empty($product_id) )
    	{
    		
    	}
    	else 
    	{
	    	//$my_car = unserialize(Session::get('car'));
	    	$my_car = unserialize($_SESSION['car']);
	    	if( !array_key_exists($product_id, $my_car))
	    	{
	    		//echo Common::_toJSON($info);
		    	//die;
	    	}
	    	else
	    	{
	    		unset($my_car[$product_id]);
	    		//Session::set('car', serialize( $my_car ));
	    		$_SESSION['car'] = serialize($my_car);
	    		
	    		$info = array('status'=>'success', 'msg'=>'操作成功');
	    		//echo Common::_toJSON($info);
	    		//die;
	    	}
    	}
    	
    	echo Common::_toJSON($info);
    	
    	
    }
    
    
    /**
     * 购物车页面
     * Enter description here ...
     */
    public function shopping_car()
    {
    	//$user = Session::get('mobile_user');
    	$user = $_SESSION['mobile_user'];
//    	if(empty($user))
//    	{
//    		$this->redirect("mobile/login");
//    		die;
//    	}
    	
    	$model = new Model();
    	//$my_car = unserialize(Session::get('car'));
    	$my_car = unserialize($_SESSION['car']);
    	$total_zje = 0.00;
    	foreach($my_car as $key=>$value)
    	{
    		$product_obj = $model->table("products")->where("id=".$key)->find();
    		$goods_id = $product_obj['goods_id'];//商品id
    		$goods_obj = Common::getGoodsInfo($goods_id);
    		$my_car[$key]['name'] = $goods_obj['name'];
    		$my_car[$key]['sell_price'] = $product_obj['sell_price'];
    		$my_car[$key]['img'] = $goods_obj['img'];
    		$my_car[$key]['spec'] = Common::getSpecByProductId($product_obj['id']);
    		$my_car[$key]['product_id'] = $product_obj['id'];
    		
    		$total_zje += $product_obj['sell_price'];
    	}
    	
    	$this->assign("my_car", $my_car );
    	
    	$this->assign('total_zje', sprintf("%.2f",$total_zje) );
    	$this->redirect();
    }
    
    
    /**
     * 提交订单页面
     * Enter description here ...
     */
    public function sub_order()
    {
    	//从session中得到user_id
    	//$user = Session::get('mobile_user');
    	$user = $_SESSION['mobile_user'];
    	if( empty( $user ) )
    	{
    		$this->redirect("mobile/login");
    		die;
    	}
    	$user_id = $user['id'];
    	
    	$sub_order_list = array();
    	$json_str = Req::args("json_str");
    	
    	//Session::set('json_str', $json_str);
    	$_SESSION['json_str'] = $json_str;
    	
    	$json_str = substr($json_str, 1, strlen($json_str)-2);
    	
    	$json_str = str_replace("'", "", $json_str);
    	
    	$arr = explode(",", $json_str);
    	for($i=0,$c=count($arr); $i<$c; $i++)
    	{
    		$item = $arr[$i];
    		$item_arr = explode(":", $item);
    		$product_id = $item_arr[0];
    		$buy_num = $item_arr[1];
    		
    		$data['product_id'] = $item_arr[0];
    		$data['buy_num']    = $item_arr[1];
    		
    		//根据货品id得到该商品所属的所有信息
    		$p_g_obj = Common::getProductObjByPId( $item_arr[0] );
    		
    		$data['name']   = $p_g_obj['name'];
    		$data['img']    = $p_g_obj['img'];
    		$data['spec']   = Common::getSpecByProductId($item_arr[0]);
    		$data['sell_price'] = $p_g_obj['sell_price']; 
    		$data['goods_id']   = $p_g_obj['goods_id'];
    		$sub_order_list[]   = $data;
    	}
    	
    	$this->assign("goods_list_str", serialize($sub_order_list));
    	
    	$this->assign('sub_goods_list', $sub_order_list);
    	
    	$addr_id = intval(Req::args("addr_id"));
    	if( !empty( $addr_id ) )
    	{
    		//Session::clear('is_choose_addr');
    		unset($_SESSION['is_choose_addr']);
    		$addr_obj = Common::getUserAddrObj($addr_id);
    	}
    	else 
    	{
    		//获取用户的收货地址信息
    		$addr_obj = Common::getUserDefaultAddr( $user_id );
    	}
    	
    	$this->assign('addr_obj', $addr_obj);
    	$this->redirect();
    }
    
    
    
    
    
    
//根据商品数组对象得到商品总额等信息(自己写的)
	//创建多用户订单中的商品总额等信息
	protected static  function getGoodsTotalMoneyByPNo($array_list)
	{
		$total = 0.00;//订单总金额
		$point = 0;//积分
		$xjq = 0;//现金券
		$seller_id=0;//商家id
		foreach($array_list as $key=>$value)
		{
			$total += $value['sell_price'] * $value['nums'];
        	//$cb += $value['cb'] * $value['nums'];
        	$point += $value['point'] * $value['nums'];
        	$seller_id = $value['seller_id'];//给商家id赋值
        	//$xjq += $value['xjq'];//现金券
		}
		
		/*
		$ship_money = Common::getConfigValue("ship_money");
		if($cb < 100)
		{
			$total += $ship_money;
		}
		*/
		
		$data['seller_id'] = $seller_id;
        $data['total'] = sprintf("%.2f", $total);//订单总金额
        //$data['cb'] = $cb;//订单总彩币
        $data['point'] = $point;//订单总积分
        //$data['xjq'] = $xjq;//现金券
        return $data;
	}
    
    
    
	/**
	 * 生成订单  (多用户订单)(自己写的)
	 * Enter description here ...
	 * @param $userId
	 * @param $payment_id
	 * @param $addrId
	 * @param $intro
	 * @param $array_list
	 */
	protected static  function create_new_order($userId,$payment_id, $addrId, $intro, $array_list)
	{
		
		$model = new Model();
		//订单号
		$data['order_no'] = Common::createOrderNo();
		$data['payment'] = $payment_id;
		//用户id
		$data['user_id'] = $userId;
		
		$addressObj = Common::getAreaObjById($addrId);
		//省
		$data['province'] = $addressObj['province'];
		//市
		$data['city'] = $addressObj['city'];
		//县
		$data['county'] = $addressObj['county'];
		//邮政编码
		$data['zip'] = $addressObj['zip'];
		//简单地址
		$data['addr'] = $addressObj['addr'];
		//收货姓名
		$data['accept_name'] = $addressObj['accept_name'];
		$data['phone'] = $addressObj['phone'];
		$data['mobile'] = $addressObj['mobile'];
		//创建时间
		$data['create_time'] = date('Y-m-d H:i:s',time());
		//用户订单备注
		$data['user_remark'] = $intro;
		
		$data['status'] = 2;//待审核
		
        $data['pay_status'] = 0;//未付款
        
        
        $info = self::getGoodsTotalMoneyByPNo($array_list);
        
        //商家id
        $data['seller_id'] = $info['seller_id'];
        
        //应付商品总额
        $data['payable_amount'] = $info['total'];
        //实付商品总额
        $data['real_amount'] = $info['total'];
		//调整后的商品总额
        $data['order_amount'] = $info['total'];
		//订单中的彩币总和
        //$data['hjcb'] = $info['cb'];
        //订单中的xjq
        //$data['xjq'] = $info['xjq'];
        
//        $ship_money = Common::getConfigValue("ship_money");
//        if($info['cb'] < 100)
//        {
//        	$data['post_money'] = $ship_money;
//        }
        
        //订单积分    
        $data['point'] = $info['point'];
            
        //配送费用
        $data['payable_freight'] = 0.00;
		//实际配送费用
        $data['real_freight'] = 0.00;
        //订单类型(0普通订单 1团购订单 2限时抢购 3捆绑促销)
        $data['type'] = 0;
        //优惠券id
        $data['voucher_id'] = 0;
        //优惠券信息
        $data['voucher'] = serialize(array());
        
        //店铺自取时，店铺类型
        //$data['delivery_dp_id'] = $dp_id;
        //写入订单数据
        $order_id = $model->table("order")->data($data)->insert();
        
        //写入订单商品
        $tem_data = array();
        //如果订单中包含多商户商品
        foreach($array_list as $key=>$v)
		{	
			$tem_data['order_id'] = $order_id;
            $tem_data['goods_id'] = $v['goods_id'];//单个商品id
            $tem_data['product_id'] = $v['product_id'];//单个商品货号
            $tem_data['goods_price'] = $v['sell_price'];//单个商品零售价
            $tem_data['real_price'] = $v['sell_price'];
            //$tem_data['p_cb'] = $v['cb'];//单个商品彩币
            $tem_data['goods_nums'] = $v['nums'];//购买的商品数量
            $tem_data['goods_weight'] = $v['weight'];//商品重量
            
            $tem_data['prom_goods'] = serialize(array('real_price'=>$v['sell_price'],'note'=>'','minus'=>'-0'));
            $tem_data['spec'] = serialize($v['spec']);
           
            $model->table("order_goods")->data($tem_data)->insert();
            
		}
		
		$child_order_obj = array();
		$child_order_obj['order_no'] = $data['order_no'];//保存子订单号
		$child_order_obj['order_amount'] = $info['total'];//保存子订单金额
		$child_order_obj['seller_id'] = $v['seller_id'];
		
		//$child_order_obj['cb'] = $info['cb'];
		
		return $child_order_obj;
	}
    
    
    
    
	/**
     * 检测一个订单是否为合并订单(自己写的)
     * 满足条件：订单中必须商品种类必须大于1，且其中必须有1个以上的商家
     * Enter description here ...
     * @param unknown_type $arrayList
     */
    static  function checkIsHeBingOrder($arrayList=null)
    {
    	$model = new Model();
    	$arr=array();
    	foreach($arrayList as $key=>$value)
    	{
    		$seller_id = $model->table("goods")->where("id=".$value['goods_id'])->find()['seller_id'];
    		$arr[$seller_id] =0;
    		
    	}
    	
    	if(count($arr) > 1)return 1;
    	else return 0;
    }
    
    
    
    
    
    
    
    /**
     * 处理提交订单
     * Enter description here ...
     */
    public function order_act()
    {
    	$model = new Model();
    	
    	//$user = Session::get('mobile_user');
    	$user = $_SESSION['mobile_user'];
    	if( empty( $user ) )
    	{
    		$this->redirect('user_center');
    		die;
    	}
    	
    	$order_type = 0;//普通订单
    	//$payment_id = 1;//支付方式，默认为余额支付
    	
    	$user_id = $user['id'];
    	
    	$addr_id = intval( Req::args('addr_id') );
    	$address_obj = $model->table("address")->where("id=$addr_id")->find();
    	if( empty( $address_obj ) )
    	{
    		$info = array('status'=>'fail', 'msg'=>'选择的地址信息不正确');
    		echo Common::_toJSON( $info );
    		die;
    	}
    	//买家留言
    	$data['user_remark'] = Req::args('leave_message');
    	
    	$goods_list = unserialize( Req::args('goods_list') );
		if( empty($goods_list))
		{
			$info = array('status'=>'fail', 'msg'=>'商品为空，无法提交订单');
			echo Common::_toJSON( $info );
			die;
		}
		else
		{
		    $arr = [];
		    foreach($goods_list as  $key=>$value)
		    {
		        //商品id
		        $goods_id = $value['goods_id'];
		        
		        $goodsObj=$model->table("goods")->fields("category_id")->where("id=".$goods_id)->find();
		        //商品分类id
		        $category_id = $goodsObj['category_id'];
		        
		        $category_obj = Common::get_category_obj($category_id);
		        $path_arr = explode(",", $category_obj['path']);
		        $cid = $path_arr[1];
		        $arr[$cid] = 0;
		    }

		    if( count($arr) > 1 || count($arr) < 1 )
		    {
		        $info = array('status'=>'fail', 'msg'=>'有不同支付方式的商品存在，请分批次购买！');
    			echo Common::_toJSON( $info );
    			die;
		    }
		    //根据商品列表获取商品的支付方式
		    $payment_id = Common::get_order_payment_id($goods_list);		    

			for($i=0,$c=count($goods_list); $i<$c; $i++)
			{
				$product_id = $goods_list[$i]['product_id'];
				$buy_num    = $goods_list[$i]['buy_num'];
				$product_obj= Common::getProductObjByPId($product_id);
				if($buy_num >$product_obj['store_nums'])
				{
					$info = array( 'status'=>'fail', 'msg'=>'商品库存不足，无法提交订单' );
					echo Common::_toJSON( $info );
					die;
				}
				$goods_list[$i]['goods_id'] = $product_obj['goods_id'];
				$goods_list[$i]['sell_price'] = $product_obj['sell_price'];
				$goods_list[$i]['spec'] = $product_obj['spec'];
				$goods_list[$i]['seller_id'] = $product_obj['seller_id'];//商家user_id
				$goods_list[$i]['nums'] = $buy_num;//购物数量
				$goods_list[$i]['weight'] = $product_obj['weight'];
				$goods_obj = Common::getGoodsInfo($product_obj['goods_id']);
				$goods_list[$i]['point'] = $goods_obj['point'];
				
			}
			
			
			
			if( intval($order_type) === 0 )//普通订单
			{
				for($i=0,$c=count($goods_list); $i<$c; $i++)
				{
					//检测为合并订单
					if(self::checkIsHeBingOrder($goods_list))
                	{
                		$demoList=array();
                		for($i=0,$c=count($goods_list); $i<$c; $i++)
						{
							$productObj = $model->table("products")->fields("seller_id")->where("id=".$goods_list[$i]['product_id'])->find();
							$demoList[$productObj['seller_id']][] = $goods_list[$i];
						}
						
//						$info = array('status'=>'success', 'msg'=>$goods_list[0]['seller_id']);
//	                	echo Common::_toJSON($info);
//	                	die;
						
	                	$child_order_list=array();
	                	
	                	foreach($demoList as  $value)
	                	{
	                		//(如果存在多商家)循环生成订单,并得到子订单返回信息
	                		//dp_id 店铺自取时店铺id
							$child_order_list[] = self::create_new_order($user_id,$payment_id, $addr_id, $data['user_remark'], $value);
	                	}
	                	
	                	$cc = 0;
	                	//将n个子订单和一个合并订单信息添加到合并订单表中
						for($i=0; $i<count($child_order_list); $i++)
						{
							$order_no        = "HB".Common::createOrderNo();//订单号(重新生成新的订单号)
							$child_order_no .= $child_order_list[$i]['order_no'].",";
							$seller_id      .= $child_order_list[$i]['seller_id'].",";//所属商户id
							$order_amount   += $child_order_list[$i]['order_amount'];//订单金额
							$remark         .= "包含子订单".$child_order_list[$i]['order_no']." ";//订单备注
						}
		                
						$demo['order_no']       = $order_no;
						$demo['child_order_no'] = trim($child_order_no, ",");//该订单的子订单号连接 比如a,b
						$demo['seller_id']      = trim($seller_id, ",");//该订单所属的商家id连接 比如a,b
						$demo['order_amount']   = $order_amount;
						$demo['remark']         = $remark;
						$demo['create_time']    = date("Y-m-d H:i:s", time());
						$demo['user_id']        = $user_id;//该订单购买者的id
						
						
						//将合并订单数据保存到合并订单表中
						$model->table("demo_order")->data($demo)->insert();
						//返回合并订单表中的最后插入的订单id
						
	               		//清空购物车与表单缓存
		                if($order_type==0)
		                {
		                	unset($_SESSION['json_str']);
		                	unset($_SESSION['car']);
		                    //Session::clear('json_str');
		                    //Session::clear('car');
		                }

	                	$info = array('status'=>'success', 'msg'=>'成功提交订单');
	                	echo Common::_toJSON($info);
	                	die;
	                	
                	}
                	else//不是合并订单 
                	{
                		$real_amount = 0.00;
                		$point = 0;
                		
                		for($i=0,$c=count($goods_list); $i<$c; $i++)
						{
							$sell_price  = $goods_list[$i]['sell_price'];
							$nums        = $goods_list[$i]['buy_num'];
							$real_amount += $sell_price * $nums;
							$weight = $goods_list[$i]['weight'] * $nums;//计算重量
							$point += $goods_list[$i]['point'] * $nums;
						}
						
	                	//填写订单
		                $data['order_no'] = Common::createOrderNo();
	                    $data['user_id'] = $user_id;
		                $data['seller_id'] = $goods_list[0]['seller_id'];//商家user_id
		                $data['payment'] = $payment_id;
		                $data['status'] = 2;
		                $data['pay_status'] = 0;
		                $data['accept_name'] = $address_obj['accept_name'];
		                //$data['phone'] = $address['phone'];
		                $data['mobile'] = $address_obj['mobile'];
		                $data['province'] = $address_obj['province'];
		                $data['city'] = $address_obj['city'];
		                $data['county'] = $address_obj['county'];
		                $data['addr'] = Filter::text($address_obj['addr']);
		                $data['zip'] = $address_obj['zip'];
		                $data['payable_amount'] = $real_amount;//应付
		                
		                //计算运费
	                	$fare = new Fare($weight);
	                	//$payable_freight = $fare->calculate($addr_id);//运费
	                	//$real_freight = $payable_freight;//运费
	                	$payable_freight = 0.00;//运费
	                	$real_freight = 0.00;//运费
	                	
		                $data['payable_freight'] = $payable_freight;
		                $data['real_freight'] = $real_freight;
		                
		                $order_amount = $real_amount + $payable_freight;
		                
		                $data['create_time'] = date('Y-m-d H:i:s');
		                $data['user_remark'] = $data['user_remark'];
		                $data['is_invoice'] = $is_invoice;
		                
		                //$data['taxes'] = $tax_fee;
		
		                //$data['discount_amount'] = 0;//打折后付款
		
		                $data['order_amount'] = $order_amount;
		                $data['real_amount'] = $real_amount;//实际付款
		
		                $data['point'] = $point;
		                $data['type'] = $order_type;
		                //$data['voucher_id'] = $voucher_id;
		                //$data['voucher'] = serialize($voucher);
						$data['seller_id'] = $goods_list[0]['seller_id'];
						$data['point'] = $point;
		
		                //写入订单数据
		                $order_id = $model->table("order")->data($data)->insert();
		                
		                //写入订单商品
		                $tem_data = array();
		
		                foreach ($goods_list as $item) 
		                {
		                    $tem_data['order_id']     = $order_id;
		                    $tem_data['dp_id']        = Common::getGoodsInfo($item['goods_id'])['u_dp_id'];//写入商品所属店铺id
		                    $tem_data['goods_id']     = $item['goods_id'];
		                    $tem_data['product_id']   = $item['product_id'];
		                    $tem_data['goods_price']  = $item['sell_price'];
		                    //$tem_data['real_price'] = $item['real_price'];
		                    $tem_data['real_price']   = $item['sell_price'];
		                    $tem_data['goods_nums']   = $item['nums'];
		                    $tem_data['goods_weight'] = $item['weight'];
		                    //$tem_data['prom_goods']   = serialize($item['prom_goods']);
		                    $tem_data['prom_goods'] = serialize(array('real_price'=>$item['sell_price'],'note'=>'','minus'=>'-0'));
		                    //$tem_data['spec']         = serialize($item['spec']);
		                    $tem_data['spec']         = $item['spec'];
		                    $model->table("order_goods")->data($tem_data)->insert();
		                }
		                
                	//清空购物车与表单缓存
		                if($order_type==0)
		                {
		                	unset($_SESSION['json_str']);
		                	unset($_SESSION['car']);
		                    //Session::clear('json_str');
		                    //Session::clear('car');
		                }
						$info = array('status'=>'success', 'msg'=>'成功提交订单');
	                	echo Common::_toJSON($info);
	                	die;
						
                	}
				}
			}
			
		}
    	

    	
    } 
    
    
    /**
     * 所有订单列表
     * Enter description here ...
     */
    public function order_list()
    {
    	//$user = Session::get('mobile_user');
    	
    	$user = $_SESSION['mobile_user'];
    	if( empty( $user ) )
    	{
    		$this->redirect("mobile/user_center");
    		die;
    	}
    	
    	$type = intval( Req::args('type') );
    	
    	$user_id = $user['id'];
    	
    	$model = new Model();
    	
    	$order_list = $model->table("order")->where("user_id=$user_id")->order("id desc")->select();
    	
    	$demo_arr = array();
    	
    	for($i=0,$c=count($order_list); $i<$c; $i++)
    	{
    		$order_id     = $order_list[$i]['id'];
    		
    		$order_goods_list = $model->table("order_goods")->fields("goods_id")->where("order_id=$order_id")->select();
			
    		$goods_id = $order_goods_list[0]['goods_id'];
    		$goods_obj = Common::getGoodsInfo($goods_id);
    		$order_list[$i]['img'] = $goods_obj['img'];

    		$goods_name_str = '';
    		for($j=0,$cc=count($order_goods_list); $j<$cc; $j++)
    		{
    			$gid = $order_goods_list[$j]['goods_id'];
    			$gobj = Common::getGoodsInfo($gid);
    			
    			$goods_name_str .= $gobj['name']." ";
    		}
			
    		$order_list[$i]['goods_name_str'] = $goods_name_str;
    		
    		$order_no     = $order_list[$i]['order_no'];
    		$order_stauts = intval( Common::getOrderStateByONo($order_no));
    		
    		$order_list[$i]['order_status'] = $order_stauts;
    		if( empty($type) || $type===0 )
    		{
    			$demo_arr[] = $order_list[$i];
    		}
	    	elseif( $type === 1 )//待付款订单
	    	{
	    		if( $order_stauts === 1 )
	    		{
	    			$demo_arr[] = $order_list[$i];
	    		}
	    	}
	    	elseif( $type === 2 )//待发货
	    	{
	    		if( $order_stauts === 2 )
	    		{
	    			$demo_arr[] = $order_list[$i];
	    		}
	    	}
    		elseif( $type === 3 )//待收货
	    	{
	    		if( $order_stauts === 3 )
	    		{
	    			$demo_arr[] = $order_list[$i];
	    		}
	    	}
    		elseif( $type === 4 )//待评价
	    	{
	    		if( $order_stauts === 4 )
	    		{
	    			$review_obj = $model->table("review")->where("order_no='{$order_no}'")->find();
	    			if(!empty( $review_obj['content']) && !empty($review_obj['coment_time']))
	    			{
	    				$demo_arr[] = $order_list[$i];
	    			}
	    		}
	    	}
    		elseif( $type === 5 )//退、换状态
	    	{
	    		if( $order_stauts === 5 || $order_stauts===6 )
	    		{
	    			$demo_arr[] = $order_list[$i];
	    		}
	    	}
    	}
    	$this->assign("order_type", $type);
    	$this->assign('order_list', $demo_arr);
    	//$this->assign('type', $type);
    	$this->redirect();
    	
    }
    
    
    
    
    /**
     * 订单详情页面
     * Enter description here ...
     */
    public function order_detail()
    {
    	$id = intval(Req::args('id'));
    	
    	$model = new Model();
    	$order_obj = $model->table("order")->where("id=$id")->find();
    	$doc_invoice_obj = $model->table("doc_invoice")->where("order_id=$id")->find();
    	$order_obj['express_no'] = $doc_invoice_obj['express_no'];//物流单号
    	$order_obj['express_company'] = $model->table("express_company")->where("id=".$doc_invoice_obj['express_company_id'])->find()['name'];
    	
    	$order_obj['order_status'] = Common::getOrderStateByONo($order_obj['order_no']);
    	
    	$arr = PostCard::ge_post_info($doc_invoice_obj['express_no']);
    	$this->assign('post_info', $arr['data']);
    	
    	$goods_list = Common::getGoodsListByOId( $id );
    	
    	$this->assign('goods_list', $goods_list);
    	$this->assign('order_obj', $order_obj);
    	
    	$this->redirect();
    }
    
    
    /**
     * 更多商品页面
     * Enter description here ...
     */
    public function more_products()
    {
        /*
    	$cid = Req::args('cid');
    	$category_name = Common::getCategoryNameByCid($cid);
    	$goods_list = Common::getGoodsListByClassifyId($cid);
        */
        
        $id = Req::args('id');
        $model = new Model();
        $obj = $model->table("app_ad")->where("id=$id")->find();
        $arr = explode(",", $obj['content']);
        $goods_list = [];
        for($i=0,$c=count($arr); $i<$c; $i++)
        {
            $goods_list[]=Common::getGoodsInfo($arr[$i]);
        }
    	//print_r($goods_list);die;
    	$this->assign('goods_list', $goods_list);
    	$this->assign('category_name', $obj['name']);
    	$this->redirect();
    }
    
    
    static function array_sort($arr,$keys,$type='asc')
    { 
	    $keysvalue = $new_array = array();
	    foreach ($arr as $k=>$v)
	    {
	        $keysvalue[$k] = $v[$keys];
	    }
	    if($type == 'asc')
	    {
	        asort($keysvalue);
	    }else
	    {
	        arsort($keysvalue);
	    }
	    reset($keysvalue);
	    foreach ($keysvalue as $k=>$v)
	    {
	        $new_array[$k] = $arr[$k];
	    }
	    return $new_array; 
	} 
    
    
    /**
     * 搜索页面
     * Enter description here ...
     */
    public function search_products()
    {
    	$sql = '';
    	$demo='';
    	$search_text = strval( Req::args('search_text') );
    	
    	$type = intval( Req::args('type') );
    	
    	if(!empty($search_text))
    	{
	    	if( strpos($search_text," ") )
	    	{
	    		
	    		$arr= explode(" ", $search_text);
	    		for($i=0,$c=count($arr); $i<$c; $i++)
	    		{
	    			$a = $arr[$i];
	    			$demo .="name like '%$a%' or ";
	    		}
	    		$demo = substr($demo,0,strlen($demo)-4);
	    	}
	    	else 
	    	{
	    		$demo ="name like '%$search_text%'";
	    	}
	    	
	    	$model = new Model();
	    	
	    	$goods_list = $model->table("goods")->where("$demo")->select();
	    	
	    	if( $type === 1 )
	    	{
		    	for($i=0,$c=count($goods_list); $i<$c; $i++)
		    	{
		    		$sell_num = Common::getGoodNumByGId($goods_list[$i]['id']);
		    		$goods_list[$i]['sell_num'] = $sell_num?$sell_num:0;
		    	}
		    	
		    	$goods_list = self::array_sort($goods_list,'sell_num');
	    	}
	    	elseif( $type === 2 )
	    	{
	    		$goods_list = self::array_sort($goods_list,'sell_price');
	    	}
	    	
    	}
    	$this->assign('goods_list', $goods_list);
    	$this->assign('search_text', $search_text);
    	
    	$this->redirect();
    }
    
    
    /**
     * 商品分类页面
     * Enter description here ...
     */
    public function goods_category()
    {
    	$first_level_goods_category = Common::getFirstLevelGoodsCategory();
    	$id = intval(Req::args("id"));
    	if( empty($id) )
    	{
    		$id = $first_level_goods_category[0]['id'];
    		$this->assign("cid", 0);
    	}
    	else 
    	{
    		$this->assign("cid", $id);
    	}
    	
    	$second_level_goods_category = self::getSecondLevelGoodsCategoryByFirstLevel( $id );
    	for($i=0,$c=count($second_level_goods_category); $i<$c; $i++)
    	{
    		$s_cid = $second_level_goods_category[$i]['id'];
    		$t_obj = self::getThirdLevelGoodsCategoryBySecondLevel($s_cid);
    		$second_level_goods_category[$i]['t_cid_list'] = $t_obj;
    	}
    	
    	//print_r($second_level_goods_category);die;
    	
    	$this->assign('first_level_goods_category', $first_level_goods_category);
    	$this->assign('second_level_goods_category', $second_level_goods_category);
    	
    	$this->redirect();
    }
    
    
    /**
     * 根据商品1级分类得到商品二级分类
     * Enter description here ...
     */
    public static function getSecondLevelGoodsCategoryByFirstLevel($cid)
    {
    	$model = new Model();
    	$category_list = $model->table("goods_category")->where("parent_id=$cid")->select();
    	return $category_list;
    	//$this->assign("second_level_goods_category", $category_list);
    	//$this->redirect();
    }
    
    
	/**
     * 根据商品2级分类得到商品3级分类
     * Enter description here ...
     */
    public static function getThirdLevelGoodsCategoryBySecondLevel($cid)
    {
    	$model = new Model();
    	$category_list = $model->table("goods_category")->where("parent_id=$cid")->select();
    	//$this->assign("third_level_goods_category", $category_list);
    	//$this->redirect();
    	return $category_list;
    }
    
    /**
     * 分类商品页面
     * Enter description here ...
     */
    public function category_products()
    {
    	$type = intval( Req::args('type') );
    	
    	
    	$cid = intval( Req::args('cid') );
    	$category_name = Common::getCategoryNameByCid($cid);
    	$this->assign('category_name', $category_name);
    	
    	$goods_list = Common::getGoodsListByThirdLevelCategoryId($cid);
    	
    	if( $type === 1 )
	    {
	    	for($i=0,$c=count($goods_list); $i<$c; $i++)
	    	{
	    		$sell_num = Common::getGoodNumByGId($goods_list[$i]['id']);
	    		$goods_list[$i]['sell_num'] = $sell_num?$sell_num:0;
	    	}
	    	
	    	$goods_list = self::array_sort($goods_list,'sell_num','desc');
    	}
    	elseif( $type === 2 )
    	{
    		$goods_list = self::array_sort($goods_list,'sell_price');
    	}
    	
    	$this->assign('goods_list', $goods_list);
    	
    	$this->redirect();
    	
    	
    }
    
    /**
     * 提现页面
     * Enter description here ...
     */
    public function withdraw()
    {
    	//$user = Session::get("mobile_user");
    	//print_r($user);die;
    	$this->redirect();
    	
    }
    
    /**
     * 提现处理方法
     * Enter description here ...
     */
    public function withdraw_do()
    {
    	
    	//Filter::form();
        $account = floatval(Req::args('account'));
        $name = Filter::txt(Req::args('name'));
        $type_name = Filter::txt(Req::args('type_name'));
        $account = Filter::txt(Req::args('account'));
        $amount = Filter::float(Req::args('amount'));
        $pass2 = Filter::txt(Req::args('pass2'));
        
        $tx_flag = intval( Common::getConfigJjsetValue("jjset_txflag") );
        if($tx_flag === 0)
        {
            $info = array('status'=>'fail','msg'=>'提现功能暂时还不能操作');
            echo JSON::encode($info);
            die;
        }
        if($amount < 100 || $amount % 10 != 0)
        {
            $info = array('status'=>'fail','msg'=>'提现金额必须大于等于100且为10的倍数');
            echo JSON::encode($info);
            die;
        }
        
        $txf      = $amount*(Common::getConfigJjsetValue('jjset_txf')/100);
        $sj_money = $amount-$txf;
        

        $model = new Model('customer');
        $customer = $model->where("user_id=".$this->mobile_user['id'])->find();
        if (Common::getPass2($this->mobile_user['id'],$pass2)==0) {
            $info = array('status'=>'fail','msg'=>'交易密码不正确');
        }elseif($customer['balance']<$amount){
            $info = array('status'=>'fail','msg'=>'提现金额超出账户余额');
        }else{
            $obj = $model->table("withdraw")->where("status=0 and user_id=".$this->mobile_user['id'])->find();
            if($obj){
                $info = array('status'=>'fail','msg'=>'上次申请的提现，还未处理，处理后才可再申请。');
            }else{
                $model->table("customer")->where("user_id=".$this->mobile_user['id'])->data(array('balance'=>"`balance`-$amount"))->update();
                $data = array('name'=>$name,'type_name'=>$type_name,'account'=>$account,'txf'=>$txf,'sq_money'=>$amount,'amount'=>$sj_money,'time'=>date('Y-m-d H:i:s'),'user_id'=>$this->mobile_user['id']);
                $model->table("withdraw")->data($data)->insert();
                $info = array('status'=>'success','msg'=>'申请成功.');
            }
        }
        echo JSON::encode($info);
    }
    
    
    /**
     * 提现记录页面
     * Enter description here ...
     */
    public function withdraw_list()
    {
        /*
    	$model = new Model();
    	$withdraw_list = $model->table("withdraw")->where("user_id=".$this->mobile_user['id'])->select();
    	$this->assign('withdraw_list', $withdraw_list);
    	*/
    	$this->redirect();	
    }
    
    
    /**
     * 充值处理方法
     * Enter description here ...
     */
    public function recharge_do()
    {
    	$info = array('status'=>'error','msg'=>'暂时不支持此功能');
    	echo JSON::encode($info);
    	die;
    	$user_id = intval( Req::args('user_id') );
    	//充值金额
    	$money = floatval( Req::args('money') );
    	//支付类型
    	$payment_id = intval( Req::args('payment_id') );
    	
    }
    
    
    
    /**
     * 充值记录页面
     * Enter description here ...
     */
    public function recharge_list()
    {
    	$model = new Model();
    	/*
    	$user_id = $this->mobile_user['id'];
    	$list = $model->table("recharge")->where("user_id=$user_id")->select();
    	
    	$this->assign('list', $list);
    	*/
    	$this->redirect();
    }
    
    /**
     * 币种转换处理方法
     * Enter description here ...
     */
    public function trans_do()
    {
    	
        $zh_from = Filter::txt(Req::args('zh_from'));
        $zh_get = Filter::txt(Req::args('zh_get'));
        $amount = Filter::txt(Req::args('amount'));
        $pass2 = Filter::txt(Req::args('pass2'));
        $user_id = intval(Req::args('user_id'));
        
        $mc_f=Common::getBzName($zh_from);
        $mc_g=Common::getBzName($zh_get);
        $cx_suoding=Common::getConfigJjsetValue("jjset_cx_sd");
        $model = new Model('customer');
        $customer = $model->where("user_id=".$this->mobile_user['id'])->find();

        if (Common::getPass2($this->mobile_user['id'],$pass2)==0) {
            $info = array('status'=>'fail','msg'=>'二级密码不正确');
        }elseif($customer[$zh_from]<$amount){
            $info = array('status'=>'fail','msg'=>'转换金额超出'.$mc_f.'余额');
        }elseif($zh_from=='u_cx' && $customer['u_cx']-$cx_suoding<$amount){
            $info = array('status'=>'fail','msg'=>'转换金额超出'.$mc_f.'余额');
        }else{
            $ye=$customer[$zh_from]-$amount;
            if ($zh_get=='gwb') {
                $uget=$customer[$zh_get]+$amount*3;
            }elseif ($zh_get=='xxb') {
                $uget=$customer[$zh_get]+$amount*2;
            }else{
                $uget=$customer[$zh_get]+$amount;
            }
            $model->where("user_id=".$this->mobile_user['id'])->data(array($zh_from=>"`$zh_from`-$amount",$zh_get=>$uget))->update();
            $data = array('user_id'=>$this->mobile_user['id'],'ye'=>$ye,'zh_lx'=>$mc_f." → ".$mc_g,'zh_money'=>$amount,'zh_time'=>date('Y-m-d H:i:s'));
            $model->table("zh")->data($data)->insert();
            $info = array('status'=>'success','msg'=>'转换成功.');
        }

        echo JSON::encode($info);
    }
    
    /**
     * 转账处理页面
     * Enter description here ...
     */
    function zz_do()
    {
    	//用户转账的账户类型,通用积分
        $zz_account_type = "currency_point";
        //Filter::form();
        //接受用户
        $toname = Filter::txt(Req::args('zz_toname'));
        $amount = Filter::float(Req::args('zz_amount'));
        $pass2 = Filter::txt(Req::args('zz_pass2'));
        $bz = Filter::txt(Req::args('zz_bz'));
        
        $from_user_id = intval(Req::args('user_id'));
        
        $validate_code = Req::args('validate_code');//短信验证码
        
        
            $u=$this->model->table("user")->where("name='$toname'")->find();
            if ($u) {
                
                
                /********短信验证码检测模块*********/
                $model = new Model();
                $uname = $this->mobile_user['name'];
                //判断短信验证码是否正确
                $sms_code_obj = $model->table("sms_code")->where("mobile='{$uname}' and sms_code='{$validate_code}' and sms_is_used=0")->find();
                if(empty($sms_code_obj))
                {
                    $info = array('status'=>'fail','msg'=>'手机短信验证码不正确！');
                    echo JSON::encode($info);
                    die;
                }
                else
                {
                    if(strtotime($sms_code_obj['sms_close_time']) < time())
                    {
                        $info = array('status'=>'fail','msg'=>'验证码已过期，请重新获取！');
                        echo JSON::encode($info);
                        die;
                    }
                }
                
                
                $toid=$u['id'];
                //$from_user_id = intval($this->user['id']);
                if($from_user_id === intval($toid))
                {
                    $info = array('status'=>'fail','msg'=>'不能给自己转账！');
                    echo JSON::encode($info);
                    die;
                }
                
                $model = new Model();
                $obj = Common::get_user_obj($from_user_id);
                if ($obj) {
                    if (Common::getPass2($this->mobile_user['id'],$pass2)!=0) {
                        if ($amount>$obj[$zz_account_type]) 
                        {
                            $info = array('status'=>'fail','msg'=>'余额不足！');
                        }
                        else
                        {
                            $this->model->table("customer")->data(array($zz_account_type=>"`$zz_account_type`-$amount"))->where("user_id=".$from_user_id)->update();
                            $this->model->table("customer")->data(array($zz_account_type=>"`$zz_account_type`+$amount"))->where("user_id=".$toid)->update();
                            
                            $data = array('bz'=>$bz,'lx'=>$zz_account_type,'uname'=>$obj['name'],'je'=>$amount,'time'=>date('Y-m-d H:i:s'),'toname'=>$toname);
                            
                            //转出用户id
                            $data['from_user_id'] = $from_user_id;
                            
                            //转入用户id
                            $data['to_user_id']   = $toid;
                            
                            $this->model->table("zz")->data($data)->insert();
                            
                            //修改短信验证码状态
                            $result4 = $model->table("sms_code")->data(['sms_is_used'=>1])->where("id=".$sms_code_obj['id'])->update();
                            
                            $info = array('status'=>'success','msg'=>'转账成功！');
                        }
                    }else{
                        $info = array('status'=>'fail','msg'=>'交易密码错误！');
                    }
                }
            }else{
                $info = array('status'=>'fail','msg'=>'接收人不存在，请核实！');
            }

        echo JSON::encode($info);
    }
    
    /**
     * 币种转换记录页面
     * Enter description here ...
     */
    public function trans_list()
    {
        /*
    	$model = new Model();
    	$list = $model->table("zh")->where("user_id=".$this->mobile_user['id'])->select();
    	$this->assign('list', $list);
    	*/
    	$this->redirect();
    }
    
    
	/**
     * 转账记录页面
     * Enter description here ...
     */
    public function zz_list()
    {
        /*
    	$model = new Model();
    	$name = $this->mobile_user['name'];
    	$list = $model->table("zz")->where("uname='{$name}'")->select();
    	$this->assign('list', $list);
    	*/
    	$this->redirect();
    }
    
    
    /**
     * 奖金记录页面
     * Enter description here ...
     */
    public function jj_list()
    {
    	$model = new Model();
    	
    	$list = $model->table("jjmx")->where("user_id=".$this->mobile_user['id'])->order("id desc")->select();
    	
    	$this->assign('list', $list);
    	$this->redirect();
    }
    
    
    /**
     * 收藏商品列表
     * Enter description here ...
     */
    public function my_attention()
    {
    	$model = new Model();
    	$list  = $model->table("attention")->where("user_id=".$this->mobile_user['id'])->select();
    	for($i=0,$c=count($list); $i<$c; $i++)
    	{
    		$goods_id = $list[$i]['goods_id'];
    		$goods_obj = Common::getGoodsInfo($goods_id);
    		$list[$i]['goods_obj']= $goods_obj;
//    		$list[$i]['img'] = $goods_obj['img'];
//    		$list[$i]['name'] = $goods_obj['name'];
//    		$list[$i]['sell_price'] = $goods_obj['sell_price'];
    	}
    	$this->assign('list', $list);
    	$this->redirect();
    }
    
    
    /**
     * 收藏商品列表
     * 
     */
    public function attention_do()
    {
    	$user_id = $this->mobile_user['id'];
    	if( empty( $user_id ) )
    	{
    		$info = array('status'=>'fail','msg'=>'您还没有登录');
    		echo JSON::encode($info);
    		die;
    	}
    	$goods_id = intval( Req::args('goods_id') );
    	
    	$model  = new Model();
    	$result = $model->table("attention")->where("user_id=$user_id and goods_id=$goods_id")->find();
    	if($result)
    	{
    		$info = array('status'=>'success','msg'=>'操作成功');
    	}
    	else 
    	{
    		$data = array('user_id'=>$user_id, 'goods_id'=>$goods_id, 'time'=>date('Y-m-d H:i:s',time()));
    		$res = $model->table("attention")->data( $data )->insert();
    		if( $res )
    		{
    			$info = array('status'=>'success','msg'=>'操作成功');
    		}
    		else
    		{
    			$info = array('status'=>'fail','msg'=>'操作失败');
    		}
    	}
    	echo JSON::encode($info);    	
    }
    
    
    
    /**
     * 我的推荐的列表
     * Enter description here ...
     */
    public function tjr_list()
    {
    	$model = new Model();
    	
    	$user_id = $this->mobile_user['id'];
    	$list = $model->query("select u.name,u_lx,u.u_tjrs,c.real_name,c.reg_time from zyk_user as u,zyk_customer as c where u.id=c.user_id and u.tjr_id=$user_id order by u.id desc;");
    	
    	$this->assign('list', $list);
    	$this->redirect();
    }
    
	    
    
    /**
     * 二维码推广页面
     * Enter description here ...
     */
    public function binary_share()
    {
    	$this->redirect();
    }
    
    
    /**
     * 公司简介页面
     * Enter description here ...
     */
    public function company_desc()
    {
    	$model = new Model();
    	$obj = $model->table("article")->where("title like '%公司%简介%'")->find();
    	$this->assign('obj', $obj);
    	$this->redirect();
    }
    
    
    /**
     * 留言页面
     * Enter description here ...
     */
    public function leave_message()
    {
    	$model = new Model();
    	$ly_list = $model->table("ly")->where("user_id=".$this->mobile_user['id'])->select();
    	$this->assign('ly_list', $ly_list);
    	$this->redirect();
    }
    
    
    /**
     * 处理提交的留言的方法
     * Enter description here ...
     */
    public function ly_act()
    {
    	$user_id = $this->mobile_user['id'];
    	$question = Filter::sql(Req::args('question'));
    	$ask_time = date("Y-m-d H:i:s", time());
    	$model = new Model();
    	$result = $model->table("ly")->data(array('user_id'=>$user_id, 'question'=>$question,'ask_time'=>$ask_time))->insert();
    	if($result)
    	{
    		$info = array('status'=>'success','msg'=>'操作成功');
    	}
    	else
    	{
    		$info = array('status'=>'error','msg'=>'操作失败');
    	}
    	echo JSON::encode($info);
    }
    
    /*
    /**
     * 手机端网页注册页面
     * Enter description here ...
     */
    /*
    public function reg()
    {
    	$tjr_name = Filter::text( Req::args('tjr_name') );
    	$model = new Model();
    	if( empty( $tjr_name ) )
    	{
    		
    	}
    	else
    	{
    		$this->assign('tjr_name', $tjr_name);

    	}
    	$this->redirect();
    }
    */
    
    /**
     * 手机网页端下载APP
     * Enter description here ...
     */
    /*
    public function download()
    {
    	$model =new Model();

        $m = new Model("version");

        $obj=$model->query("select max(version_code) as max_version_code from zyk_version");

        $result = $m->where("version_code=".$obj[0]['max_version_code'])->find();

        $config=Config::getInstance();

		$domain=$config->get("domain");

        $url=$domain.$result['url']; 
        $this->assign('download_url', $url);
        $this->redirect();
    }
    */
    
    /**
     * 订单支付页面
     * Enter description here ...
     */
    public function pay_order()
    {
    	$id = intval( Req::args('order_id') );
    	$model = new Model();
    	$order_obj = $model->table("order")->where("id=$id")->find();
    	
    	//订单编号
    	$this->assign("order_no", $order_obj['order_no']);
    	$this->assign("order_amount", $order_obj['order_amount']);
    	//$this->assign("order_amount", 0.01);
    	
    	$order_goods_list = $model->table("order_goods")->where("order_id=".$id)->limit("1")->select();
    	$goods_obj = $model->table("goods")->where("id=".$order_goods_list[0]['goods_id'])->find();
    	$goods_name = $goods_obj['name'];
    	
    	$this->assign("goods_name", $goods_name);
    	
    	
    	/*
    	$xjb_bili = Common::getConfigJjsetValue("jjset_zf_balance")/100;
    	$gwb_bili = Common::getConfigJjsetValue("jjset_zf_gwb")/100;
    	$order_obj['xjb'] = $order_obj['order_amount'] * $xjb_bili;
    	$order_obj['gwb'] = $order_obj['order_amount'] * $gwb_bili;
    	*/
    	$this->assign('order_obj', $order_obj);
    	$this->redirect();
    }
    
    
    
    /**
     * 支付处理方法
     * Enter description here ...
     */
    public function pay_do()
    {
        
        //订单id
    	$order_id  = intval( Req::args('order_id') );
    	//支付类型id
    	$payment_id = intval( Req::args('payment_id') );
    	//用户id
    	$user_id = $this->mobile_user['id'];
    	$model = new Model();
    	
    	/*
    	$user_obj     = $model->table("user")->where("id=$user_id")->find();
    	$customer_obj = $model->table("customer")->where("user_id=$user_id")->find();
    	$balance      = $customer_obj['balance'];
    	*/
    	
    	$user_obj = Common::get_user_obj($user_id);
    	$balance  = $user_obj['balance'];
    	    	
    	//二级密码
    	$pass2 = strval( trim( Req::args('pass2') ) );
    	//只有余额支付才判断二级密码
//     	if($payment_id === 1)
//     	{
        	if( strval($user_obj['passwordtwo']) !== strval(md5( $pass2 )))
        	{
        		$info = array('status'=>'error','msg'=>'二级密码不正确');
        		echo JSON::encode($info);
        		die;
        	}
//     	}
    	
    	
    	//订单对象
    	$order_obj = $model->table("order")->where("id=$order_id")->find();
    	if(empty($order_obj))
    	{
    	    $info = array('status'=>'error','msg'=>'该订单不存在');
    	    echo JSON::encode($info);
    	    die;
    	}
    	
    	
    	if($payment_id !== intval($order_obj['payment']) )
    	{
    	    $info = array('status'=>'error','msg'=>'支付方式有误');
    	    echo JSON::encode($info);
    	    die;
    	}
    	
    	//订单金额
    	$order_amount = floatval($order_obj['order_amount']);
    	//订单编号
    	$order_no = $order_obj['order_no'];
    	
    	if($payment_id === 10 || $payment_id === 11)
    	{
    	    $payment_obj  = Common::get_payment_obj_by_id($payment_id);
    	    	
    	    $demo_account_type = $payment_obj['pay_zd'];
    	    //临时支付账户余额
    	    $demo_pay__ye = $user_obj[ $demo_account_type ];
    	    	
    	    if($demo_pay__ye < $order_amount)
    	    {
    	        $info = array('status'=>'error','msg'=>'账户余额不足！');
    			echo JSON::encode($info);
    			die;
    	    }
    	}
    	
    	
    	
    	if($payment_id === 1)//预存款支付
    	{
    		
    		//$xjb = floatval( Req::args('xjb') );//现金币
    		//$gwb = floatval( Req::args('gwb') );//购物币
    		//如果订单金额大于账户余额
    		if( $balance <$order_amount )
    		{
    			$info = array('status'=>'error','msg'=>'账户余额不足,请选择其它支付方式！');
    			echo JSON::encode($info);
    			die;
    		}
    		
    		//未支付
    		if( intval( $order_obj['pay_status'] ) === 0 )
    		{
    		    $model->query("start transaction");
    			
    		    $flag = $model->table("customer")->where("user_id=".$user_id)->data(array('balance'=>"`balance`-".$order_amount))->update();

    			//记录支付日志
	            Log::balance((0-$order_amount),$user_id,'通过余额支付方式进行商品购买,订单编号：'.$order_no);
    			if( $flag )
    			{
    				$order_id = Order::updateStatus($order_no, $payment_id);
    				if( $order_id )
    				{
    				    $model->query("commit");
    					
    				    $info = array('status'=>'success','msg'=>'支付成功');
			    		echo JSON::encode($info);
			    		die;
    				}
    				else 
    				{
    				    $model->query("rollback");
    					
    				    $info = array('status'=>'error','msg'=>'支付失败');
			    		echo JSON::encode($info);
			    		die;
    				}
    			}
    			else 
    			{
    			    $model->query("rollback");
    			    
    				$info = array('status'=>'error','msg'=>'支付失败');
		    		echo JSON::encode($info);
		    		die;
    			}
    			
    		}
    		else//已支付
    		{
    			$info = array('status'=>'error','msg'=>'订单已经处理过，请查看订单信息！'.$order_id);
    			echo JSON::encode($info);
    			die;
    		}    		
    		
    	}
    	else if($payment_id === 5)//微信支付
    	{
    	    $info = array('status'=>'wx_sign','msg'=>'error');
    	    echo JSON::encode($info);
    	    die;
    	    
    	    $sign_str = self::get_pay_sign_str($user_id, $order_no, $payment_id);	    
    	    
    	    if($sign_str !== false)
    	    {
    	        $info = array('status'=>'wx_sign','msg'=>$sign_str);
    	    }
    	    else
    	    {
    	        $info = array('status'=>'wx_sign','msg'=>'error');
    	    }
    	    echo JSON::encode($info);
    	    die;
    	}
    	elseif($payment_id === 10 || $payment_id === 11)//积分支付 和消费券支付
    	{    	    
    	    $model->query("start transaction");
    	    
    	    //累减账户余额
    	    $res = $model->table("customer")->data([$demo_account_type=>"`$demo_account_type`-$order_amount"])->where("user_id=$user_id")->update();
    	    
    	    //记录支付日志
    	    Log::balance((0-$order_amount),$user_id,'通过'.$payment_obj['pay_name'].'方式进行商品购买,订单编号：'.$order_obj['order_no']);
    	    $oid = Order::updateStatus($order_obj['order_no'], $payment_id);
    	    
    	    if($oid && $res)
    	    {
    	        $model->query("commit");
    	        $info = array('status'=>'success','msg'=>'支付成功');
	    		echo JSON::encode($info);
	    		die;
    	    }
    	    else
    	    {
    	        $model->query("rollback");
    	        $info = array('status'=>'error','msg'=>'支付失败');
	    		echo JSON::encode($info);
	    		die;
    	    }    
    	}
    	
    }
    
    
    
    
    
    /**
     * 得到支付宝和微信的签名字符串
     * @param unknown $userId
     * @param unknown $token
     * @param unknown $orderNo
     * @param unknown $payType
     * @param unknown $password
     */
    public static function get_pay_sign_str($userId, $orderNo, $payType)
    {
        //Common::back_json(1, "暂时不支持在线支付功能");
        
        if(empty($userId) || empty($orderNo))
        {
            return false;
        }
            $is_he = 1;
            $model = new Model();
            	
            	
            //先查询该订单是否为合并订单号
            $demo_order_obj = $model->table("demo_order")->where("order_no='{$orderNo}' and user_id=$userId")->find();
            
            //如果该订单号是合并单
            if(!empty($demo_order_obj))
            {
                //订单详情，主要是订单价格
                $order_info = $demo_order_obj;
                $order_info['pay_status']  = $demo_order_obj['status'];
    
                //根据合并订单号获取子订单中的商品详情
                $arr = explode(",", $demo_order_obj['child_order_no']);
                for($i = 0; $i < count($arr); $i++)
                {
                    $temp = Common::getGoodsInfoByONo($arr[$i]);
                    for($j = 0; $j<count($temp); $j++)
                    {
                        $goods_info[] = $temp[$j];
                    }
                }
                
            }
            else
            {
                $is_he = 0;
    
                //如果该订单不是合并单
                $obj=$model->table("order")->where("order_no='{$orderNo}' and user_id=$userId")->find();
                if(empty($obj))
                {
                    //Common::back_json(1, "该订单不合法，获取支付信息失败");
                    return false;
                }
    
                //根据订单号获取订单详情
                $order_info = Common::getOrderInfoByONo($orderNo);
                //根据订单号获取订单中商品详情
                $goods_info = Common::getGoodsInfoByONo($orderNo);
            }
            
            $order_amount = $order_info['order_amount'];
            	
            //根据用户id获得用户信息
            $user_info = Common::getUserInfoByUId($userId);
            	
            $domain = Common::getConfigValue("domain");
            	
            	
            if(empty($goods_info))
            {
                //Common::back_json(1, "订单号非法，获取支付签名字符串失败");
                return false;
            }
            	
            if(intval($order_info['pay_status']) === 1)
            {
                //Common::back_json(1, "该订单已经付过款了");
                return false;
            }
            	
            $goodsName='';
            	
            for($i=0; $i<count($goods_info); $i++)
            {
                $goodsName .= $goods_info[$i]['name'];
            }
              	
            if($is_he === 0)
            {
                $body = $goodsName;
            }
            else
            {
                $body = $demo_order_obj['remark'];
            }
            	
            //定义签名字符串
            $sign_str='';
            
            if(intval($payType) === 5)
            {
                
                $inputObj=array(
                    'appid'=>'wxb3ea3436af647254',//公众账号id(配置)
                    'mch_id'=>'1405757402',//商户号(配置)
                    'nonce_str'=>md5(time()),//随机字符串
                    'spbill_create_ip'=>Common::get_real_ip(),
                    //'notify_url'=>'http://qcjn99.com/ss.php?con=wxnotifyurl&act=index',//接受微信支付异步通知回调地址
                    'notify_url'=>"http://www.mwantu.com/paydo/wxnotifyurl.php",
                    'trade_type'=>'APP',//交易类型
                    'body'=>$goodsName,//商品描述
                    'out_trade_no'=>$orderNo,//商户订单号
                    //'total_fee'=>$order_amount * 100,//订单金额(单位为 分 ；所有金额需要乘以100)
                    //订单价格(测试用的)
                    'total_fee'=>1,
                );
                
                
                
                 
                $weixinPay=new WeixinPay();
    
                $sign_str=$weixinPay->get_sign_str($inputObj);
    
                if($sign_str===false)
                {
                    return false;
                }
                else
                {
                    return $sign_str;
                }
            }
            else
            {
                return false;
            }
            

    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    /**
     * 签收订单
     * Enter description here ...
     */
    public function sign_order()
    {
    	$model = new Model();
    	$id = Filter::int(Req::args("id"));
    	$user_id = $this->mobile_user['id'];
    	
        $info = array('status'=>'fail','操作失败');
        
        $result = $model->table('order')->where("id=$id and user_id=".$user_id." and status=3 and pay_status=1 and delivery_status=1")->data(array('delivery_status'=>2,'status'=>4,'completion_time'=>date('Y-m-d H:i:s')))->update();
        if($result){
            
            //提取购买商品信息
            $products = $model->table('order as od')->join('left join order_goods as og on od.id=og.order_id')->where('od.id='.$id)->findAll();
            foreach ($products as $product) {
                $data = array('goods_id'=>$product['goods_id'],'user_id'=>$user_id,'order_no'=>$product['order_no'],'buy_time'=>$product['create_time']);
                $model->table('review')->data($data)->insert();
                $je = $product['goods_price'] * $product['goods_nums'];
                //Jjjs::tjj_buy($product['dp_id'],$je);//商家推荐人提成结算
            }
            //计算奖金
            $orderss = $model->table("order")->where("id=".$id)->find();
            //Pointlog::write($orderss['user_id'], $orderss['point'], '购买商品，订单：'.$orderss['order_no'].' 得'.$orderss['point'].'积分',$orderss['order_amount']);
            $info = array('status'=>'success');
        }
        echo JSON::encode($info);
    	
    }
    
    
    
    /**
     * 订单申请退款页面
     * Enter description here ...
     */
    public function refund()
    {
    	$model       = new Model();
    	$order_id    = Filter::int( Req::args('id'));
    	
    	//$user_id     = $this->mobile_user['id'];
    	//$refund_list = $model->table("doc_refund")->where("user_id=$user_id")->select();
    	$this->assign("order_id", $order_id);
    	//$this->assign('refund_list', $refund_list);
    	$this->redirect();
    	
    }
    
    /**
     * 处理退款申请的方法
     * Enter description here ...
     */
    public function refund_do()
    {
    	$model = new Model();
    	$order_id = Filter::int( Req::args('order_id') );//订单id
    	//$order_obj = $model->table("order")->where("id=$order_id")->find();
    	//$order_no = $order_obj['order_no'];//订单编号
        $order = $this->model->table("order")->where("id=$order_id and user_id = ".$this->mobile_user['id'])->find();
        $order_no = $order['order_no'];
        if($order){
            if($order['pay_status']==1){
                $refund = $model->table("doc_refund")->where("order_no='$order_no' and user_id = ".$this->mobile_user['id'])->find();
                if($refund){
                    //$this->redirect("refund",false,array('msg'=>array("warning","不能重复申请退款！")));
                    $info = array('status'=>'error', 'msg'=>"不能重复申请退款！");
                }
                else
                {
                    //Filter::form(array('text'=>'account_name|refund_account|account_bank|content','int'=>'order_no|refund_type'));
                    $data = array(
                    	'order_no'=>$order_no,
                    	'amount'=>$order['order_amount'],
                        'refund_type'=>Req::args('refund_type'),
                        'create_time'=>date('Y-m-d H:i:s'),
                        'user_id'=>$this->mobile_user['id'],
                        'order_id'=>$order['id'],
                        'content'=>Req::args('content'),
                        'pay_status'=>0
                        );
                    $model->table("doc_refund")->data($data)->insert();
                    
                    //改变订单的状态
                    $model->table("order")->data(array('pay_status'=>2))->where("id=$order_id")->update();
                    
                    //$this->redirect("refund",false,array('msg'=>array("success","申请已经成功提交,请等候处理！")));
                    $info = array('status'=>'success', 'msg'=>"申请已经成功提交,请等候处理！");
                }
            }else{
                //$this->redirect("refund",false,array('msg'=>array("warning","此订单还未支付，无法申请退款！")));
                $info = array('status'=>'error', 'msg'=>"此订单还未支付，无法申请退款！");
            }

        }else{
            //$this->redirect("refund",false,array('msg'=>array("warning","此订单编号不存在！")));
            $info = array('status'=>'error', 'msg'=>"此订单编号不存在！");
        }
        echo JSON::encode($info);
    }
    
    /**
     * 申请退款记录
     * Enter description here ...
     */
    public function refund_list()
    {
    	$model = new Model();
    	$user_id     = $this->mobile_user['id'];
    	$refund_list = $model->table("doc_refund")->where("user_id=$user_id")->select();
    	$this->assign('refund_list', $refund_list);
    	$this->redirect();
    }
    
    
    /**
     * 我的店铺
     * Enter description here ...
     */
    public function my_dp()
    {
    	$model   = new Model();
    	$user_id = $this->mobile_user['id'];
    	$dp_obj  = $model->table("dp")->where("user_id=$user_id")->find();
    	$this->assign("dp_obj", $dp_obj);
    	$this->redirect();
    }
    
    /**
     * 我的店铺商品列表页面
     * Enter description here ...
     */
    public function my_dp_products_list()
    {
    	$model   = new Model();
    	$user_id = $this->mobile_user['id'];
    	$is_online = strval( Req::args("is_online"));
    	
    	if( $is_online === 'zs' )//在售
    	{
    		$where = "is_online=0";
    	}
    	elseif($is_online === 'xj')//下架
    	{
    		$where = "is_online=1";
    	}
    	elseif($is_online === 'ds')
    	{
    		$where = "is_online=2";
    	}
    	else 
    	{
    		$where = "1=1";
    	}
    	$list = $model->table("goods")->where("u_dp_id=$user_id and $where")->select();
    	$this->assign("dp_products_list", $list);
    	$this->redirect();
    }
    
    
    /**
     * 商品上下架
     * Enter description here ...
     */
    public function set_online()
    {
        $id = Req::args("id");

        $status = Filter::int(Req::args('status'));
        // if($status!=0 && $status!=1) $status = 0;
        $model = new Model('goods');
        $on_isok=$model->fields("is_online,id")->where("id=".$id)->find()['is_online'];
        if ($on_isok<2) {
            $result = $model->data(array('is_online'=>$status))->where("id = $id and seller_id=".$this->mobile_user['id'])->update();
            if( $result )
            {
            	 $info = array('status'=>'success', 'msg'=>"操作成功");
            }
            else
            {
            	$info = array('status'=>'error', 'msg'=>"操作失败");
            }
            
        }
        echo JSON::encode($info);
    }
    
    
    
    
    
	/**
     * 删除店铺商品
     * Enter description here ...
     */
    public function del_products()
    {
    	$id = Req::args("id");
        
        $model = new Model();
        $model->table("spec_attr")->where("goods_id = $id")->delete();
        $model->table("products")->where("goods_id = $id")->delete();
        $model->table("goods")->where("id = $id ")->delete();
        
        $info = array('status'=>'success', 'msg'=>"操作成功");
            
        echo JSON::encode($info);
    }
    
    
    /**
     * 我的店铺订单列表
     * Enter description here ...
     */
    public function my_sell_order_list()
    {
    	$model = new Model();
    	$user_id = $this->mobile_user['id'];
    	$list = $model->table("order")->where("seller_id=$user_id")->select();
    	$this->assign('list', $list);
    	$this->redirect();
    }
    
    
    /**
     * 订单发货方法
     * Enter description here ...
     */
    public function order_send()
    {
    	$order_id = Req::args("id");
    	$this->assign("order_id", $order_id);
    	$this->redirect();
    }
    
    
    
    
	/**
	 * 端商家订单发货
	 * Enter description here ...
	 */
    public function order_send_do()
    {

		$model = new Model("doc_invoice");//发货表
		
		$data['admin'] = $this->mobile_user['name'];//发货人姓名
		$data['create_time'] = date('Y-m-d H:i:s');//发货时间
		$data['invoice_no'] = date('YmdHis').rand(100,999);//发货单号
		$order_id = Req::args("order_id");//订单id
		$data['order_id'] = $order_id;
		
		$orderObj = $model->table("order")->where("id=".$order_id)->find();
		
		$data['order_no'] = $orderObj['order_no'];
		$data['accept_name'] = $orderObj['accept_name'];
		$data['province'] = $orderObj['province'];
		$data['city'] = $orderObj['city'];
		$data['county'] = $orderObj['county'];
		$data['zip'] = $orderObj['zip'];
		$data['addr'] = $orderObj['addr'];
		$data['phone'] = $orderObj['phone']?$orderObj['phone']:'';
		$data['mobile'] = $orderObj['mobile'];
		
		$express_no = Req::args("express_no");//物流单号
		$data['express_no'] = $express_no;
		$express_company_id = Req::args("express_company_id");//物流公司id
		$data['express_company_id'] = $express_company_id;
		
		$model->table("doc_invoice")->data($data)->insert();


		//同步发货信息
		$order_info = $model->table("order")->where("id=$order_id")->find();
		if($order_info){
			if($order_info['trading_info']!=''){
				$payment_id = $order_info['payment'];
				$payment = new Payment($payment_id);
				$payment_plugin = $payment->getPaymentPlugin();
				$express_company = $model->table('express_company')->where('id='.$express_company_id)->find();
				if($express_company) $express = $express_company['name'];
				else $express = $express_company_id;
				//处理同步发货
				$delivery = $payment_plugin->afterAsync();
				if($delivery!=null && method_exists($delivery, "send")) $delivery->send($order_info['trading_info'],$express,'express_no');
			}
		}
		$model->table("order")->where("id=$order_id")->data(array('delivery_status'=>1,'send_time'=>date('Y-m-d H:i:s')))->update();
//		$url=Url::createUrl("/ucenter/sell_order_list");
//		echo "<script>alert('操作成功！');location.href='{$url}';</script>";
		$info = array('status'=>'success', 'msg'=>"操作成功");
        echo JSON::encode($info);
        
    }
    
    
    public function comment_order()
    {
    	$order_id = Req::args("id");
    	$this->assign('order_id', $order_id);
    	$this->redirect();
    }
    
    /**
     * 用户发表评论
     * Enter description here ...
     */
	public function comment_do()
	{
        $order_id = Filter::int(Req::args('order_id'));
        
        $model = new Model();
        
        $order_obj = $model->table("order")->where("id=$order_id")->find();
        $order_no = $order_obj['order_no'];//订单号
        $point = intval(Req::args('point'));
        if($point>5)$point = 5;
        elseif ($point<1) $point = 1;
        $content = Filter::txt(Req::args('content'));
        $content = TString::nl2br($content);

        $flage = $model->table("review")->data(array('status'=>1,'point'=>$point,'content'=>$content,'comment_time'=>date('Y-m-d')))->where("order_no='{$order_no}' and user_id=".$this->mobile_user['id'])->update();
        //$this->redirect("msg",false,array('type'=>"success",'msg'=>"评价成功！"));
        if($flage)
        {
        	$info = array('status'=>'success', 'msg'=>"操作成功");
        }
        else
        {
        	$info = array('status'=>'error', 'msg'=>"操作失败");
        }
        echo JSON::encode($info);
    }
    
    
    public function lianmeng_seller()
    {
        $city = Req::args("city");
        $county = Req::args("county");
        
        $category_id = Req::args("category_id");
        if( !empty($city) )
        {
            $this->assign("where3", "city='{$city}'");
            $this->redirect();
            die;
            //410100郑州
            //$this->assign("where3", "city='410100'");
        }
        
        if(!empty($county))
        {
            $this->assign("where3", "county='{$county}'");
            $this->redirect();
            die;
        }

        if( !empty($category_id) )
        {
            $this->assign("where3", "category_id=$category_id");
            $this->redirect();
            die;
        }
        
        $this->assign("where3", "city='410100'");
        $this->redirect();
    }
    
    
    /**
     * 申请成为商家
     */
//     function sqsj()
//     {
//         echo 'a';die;
//         $this->redirect();
//     }
    
    private $imgType1=array("image/jpeg", "image/png", "image/gif", "image/bmp");
    private $imgType2=array("jpg","png","gif","bmp");
    
    //获取扩展名
    function get_extension($file)
    {
        return substr($file, strrpos($file, '.')+1);
    }
    
    //获取文件名
    protected function get_filename($file)
    {
        return substr($file, 0, strrpos($file,'.'));
    }
    
    /**
     * 添加新的店铺
     */
    function add_dp()
    {
        
        $model = new Model();
        $user_id = Req::args('user_id');        
        $dp_dm   = Req::args("dp_dm");
        $dp_name = Req::args("dp_name");
        $dp_tel  = Req::args("dp_tel");
        $category_id = Req::args('category_id');
        $province    = Req::args("province");
        $city        = Req::args("city");
        $county      = Req::args('county');
        $dp_content  = Req::args("dp_content");
        $dp_addr     = Req::args("dp_addr");
        
        //上传图片
        if(is_uploaded_file($_FILES['dp_logo']['tmp_name']))
        {
            $upfile=$_FILES['dp_logo'];
            $yname=iconv("utf-8","gb2312",$upfile['name']);
        
            $ext=$this->get_extension($yname);
            $filename=$this->get_filename($yname);
            $firstname=substr(md5($filename.time()),0,20);
            $yname=$firstname.".".$ext;
        
            $type=$upfile['type'];
            if(!in_array($type, $this->imgType1) || !in_array($this->get_extension($yname), $this->imgType2))
            {
                $url=Url::createUrl("/mobile/sqsj");
                echo "<script>alert('上传图片类型不正确');window.location.href='{$url}';</script>";
                die;
            }
        
            $size=$upfile['size'];//上传文件的大小
            $tmp_name=iconv("utf-8","gb2312",$upfile['tmp_name']);
            if(!move_uploaded_file($tmp_name, "./data/uploads/ad/$yname"))
            {
                //$msg = array('error',"上传店铺图片失败 ");
                //$this->redirect("version_list",false,array('msg'=> $msg));
                $url=Url::createUrl("/mobile/sqsj");
                echo "<script>alert('上传店铺图片失败');window.location.href='{$url}';</script>";
                die;
            }
        
            $data['dp_logo']="./data/uploads/ad/".$yname;//服务器端储存路径
        }
        
        
        if(is_uploaded_file($_FILES['dp_pic']['tmp_name']))
        {
            $upfile=$_FILES['dp_pic'];
            $yname=iconv("utf-8","gb2312",$upfile['name']);
        
            $ext=$this->get_extension($yname);
            $filename=$this->get_filename($yname);
            $firstname=substr(md5($filename.time()),0,20);
            $yname=$firstname.".".$ext;
        
            $type=$upfile['type'];
            if(!in_array($type, $this->imgType1) || !in_array($this->get_extension($yname), $this->imgType2))
            {
//                 $this->redirect("guide_list",false,array('msg'=> array('warning',"上传图片类型不正确")));
//                 die;
                $url=Url::createUrl("/mobile/sqsj");
                echo "<script>alert('上传图片类型不正确');window.location.href='{$url}';</script>";
                die;
            }
        
            $size=$upfile['size'];//上传文件的大小
            $tmp_name=iconv("utf-8","gb2312",$upfile['tmp_name']);
            if(!move_uploaded_file($tmp_name, "./data/uploads/ad/$yname"))
            {
                //$msg = array('error',"上传店铺图片失败 ");
                //$this->redirect("version_list",false,array('msg'=> $msg));
                $url=Url::createUrl("/mobile/sqsj");
                echo "<script>alert('上传营业执照图片失败');window.location.href='{$url}';</script>";
                die;
            }
            $data['dp_pic']="./data/uploads/ad/".$yname;//服务器端储存路径
        }
        $data['user_id'] = $user_id;
        $data['dp_name'] = $dp_name;
        $data['dp_dm']   = $dp_dm;
        $data['dp_tel']  = $dp_tel;
        $data['dp_content'] = $dp_content;
        $data['category_id']= $category_id;
        $data['province']   = $province;
        $data['city']       = $city;
        $data['county']     = $county;
        $data['dp_addr']    = $dp_addr;
        $data['sq_time']    = date("Y-m-d H:i:s", time());
        //$model->query("start transaction");
        $result  = $model->table("dp")->data($data)->insert();
        //$result2 = $model->table("user")->data(array('u_lx'=>2))->where("id=$user_id")->update();
        $url=Url::createUrl("/mobile/sqsj");
        if($result)
        {
            //$model->query("commit");
            
            echo "<script>alert('申请已提交，请等待系统审核');window.location.href='{$url}';</script>";
            die;
        }
        else
        {
            echo "<script>alert('操作失败');window.location.href='{$url}';</script>";
            die;
            //$model->query("rollback");
        }
        
    }
    
    /**
     * 申请成为商家
     */
    public function sqsj()
    {
        $model = new Model();
        $user = $this->mobile_user;
        $user_id = $user['id'];
       
        $dp_obj = $model->table("dp")->where("user_id=$user_id")->find();
        if(!empty($dp_obj))
        {
            $this->assign("dp_obj", $dp_obj);
        }
        if($dp_obj['is_ok'] == 2)
        {
            $this->redirect("/mobile/user_center");
            die;
        }
        $this->redirect();
    }
    
    
    /**
     * 保存区域信息到文件缓存
     */
    public static function save_area_to_filecache()
    {
        $model = new Model();
        $province_list = $model->table("area")->select();
        $str = serialize($province_list);
        
        $fcache = FCache::getInstance();
        $fcache->set(self::$file_cache_filename, 'area', '123');
    }
    
    
    /**
     * 从文件缓存中得到区域信息
     */
    public static function get_area_from_filecache()
    {
        $fcache = FCache::getInstance();
        
        $str = strval($fcache->get('./F_CACHE_STORE', 'area'));
        echo $str;die;
        
    }
    
    
    /**
     * APP端选择城市界面
     */
    public function sel_area()
    {
        $model = new Model();
        $province_list = $model->table("area")->where("parent_id=0")->select();
        $this->assign("province_list", $province_list);
        
        $city_list = $model->table("area")->where("parent_id=".$province_list[0]['id'])->select();
        $this->assign("city_list", $city_list);
        
        $county_list = $model->table("area")->where("parent_id=".$city_list[0]['id'])->select();
        $this->assign("county_list", $county_list);
        
        $this->redirect();
    }
    
    
    
    //根据省得到市
    public function getCityByProvince2()
    {
        //<a href="#!" class="collection-item">商丘</a>
        $code = Req::args("code");
        $str = "";
        $model = new Model();
        $list = $model->table("area")->where("parent_id=$code")->select();
        
        for($i=0,$c=count($list); $i<$c; $i++)
        {
            $str .= "<a id='{$list[$i]['id']}' class='collection-item'>{$list[$i]['name']}</a>";
            //$str .="<option value='{$list[$i][id]}'>{$list[$i]['name']}</option>";
        }
        echo $str;
    }
    
    
    
    
    //根据市得到县
    public function getCountyByCity2()
    {
        $code = Req::args("code");
        
        $model = new Model();
        $list = $model->table("area")->where("parent_id=$code")->select();
        $str="";
        for($i=0,$c=count($list); $i<$c; $i++)
        {
            $str .= "<a id='{$list[$i]['id']}' class='collection-item'>{$list[$i]['name']}</a>";
            //$str .="<option value='{$list[$i][id]}'>{$list[$i]['name']}</option>";
        }
        echo $str;
    }
    
    
    
    public function zh_do()
    {
        //转换类型
        $zh_type  = intval( Filter::int(Req::args('zh_type')) );
        //$zh_get = Filter::txt(Req::args('zh_get'));
        $amount   = floatval( Filter::txt(Req::args('amount')) );
        $pass2    = Filter::txt(Req::args('pass2'));
        $model    = new Model();
        $user_id  = intval(Req::args('user_id'));
        $user_obj = Common::get_user_obj($user_id);
        
        if($zh_type === 0 && !Common::is_not_allow_do_by_time())
        {
            $info = array('status'=>'fail','msg'=>'此时不允许执行该操作');
            echo JSON::encode($info);
            die;
        }
        
        if(!Common::check_pass2($user_id, $pass2))
        {
            $info = array('status'=>'fail','msg'=>'交易密码不正确');
            echo JSON::encode($info);
            die;
        }
        /*
        if( Common::getPass2($user_id, $pass2) == 0)
        {
            $info = array('status'=>'fail','msg'=>'交易密码不正确');
            echo JSON::encode($info);
            die;
        }
        */
        
        if($zh_type < 3)
        {
            if($amount < 1)
            {
                $info = array('status'=>'fail','msg'=>'兑换金额最低不能小于1');
                echo JSON::encode($info);
                die;
            }
        }
        else
        {
            if($amount < 100 || $amount % 100 != 0)
            {
                $info = array('status'=>'fail','msg'=>'兑换金额最低不能为100，且为100的倍数');
                echo JSON::encode($info);
                die;
            }
        }
        //兑换类型
        switch($zh_type)
        {
            case 0:
                $zh_from_account_type = 'balance';
                $zh_to_account_type   = 'voucher';
                $desc                 = "账户余额 兑换 消费券";
                break;
            case 1:
                $zh_from_account_type = 'currency_point';
                $zh_to_account_type   = 'voucher';
                $desc                 = "通用积分 兑换 消费券";
                break;
            case 2:
                $zh_from_account_type = 'currency_point';
                $zh_to_account_type   = 'ok_xfjf';
                $desc                 = '通用积分 兑换 可用积分';
                break;
            case 3:
                $zh_from_account_type = 'ok_xfjf';
                $zh_to_account_type   = 'currency_point';
                $desc                 = '可用积分 兑换 通用积分';
                break;
        }
        
        /**
         * 如果账户余额不足
         */
        $ye = $user_obj[$zh_from_account_type];
        if($amount > $ye)
        {
            $info = array('status'=>'fail','msg'=>'余额不足');
            echo JSON::encode($info);
            die;
        }
        
        $from_amount = $amount;
        $to_amount   = $amount;
        
        $fbf = 0;
        /**
         * 可用积分 兑换 通用积分
         */
        if($zh_type === 3)
        {
            $fbf_bili    = Common::getConfigJjsetValue("jjset_fbf")/100;
            $fbf         = $amount * $fbf_bili;
            $to_amount   = $amount - $fbf;
        
            $data['fbf'] = $fbf;
        }
        
        
        $model->query("start transaction");
        
        $result1 = $model->table("customer")->data([$zh_from_account_type=>"`$zh_from_account_type`-$from_amount",$zh_to_account_type=>"`$zh_to_account_type`+$to_amount"])->where("user_id=$user_id")->update();
        $data['user_id'] = $user_id;
        
        $data['zh_lx']    = $zh_type;
        $data['zh_desc']  = $desc;
        //兑换金额
        $data['zh_money'] = $from_amount;
        //实际到帐金额
        $data['real_money'] = $to_amount;
        $data['zh_time']  = date('Y-m-d H:i:s');
        $result2 = $model->table("zh")->data($data)->insert();
        
        if($zh_type === 0)
        {
            $from_info = $user_obj['name'].'账户余额 兑换 消费券';
        }
        elseif($zh_type === 1)
        {
            $from_info = $user_obj['name'].'通用积分 兑换 消费券';
        }
        //产生各种奖金  账户余额兑换消费券的时候财产生各种奖金，同时升级，同时保存每日新增业绩
        //账户余额兑换消费券  和通用积分兑换消费券  这2个操作都产生奖金
        if($zh_type === 0 || $zh_type === 1)
        {
            /*
            //产生奖金
            Jjjs::exec_all_jj($user_id, $amount, $from_info);
            //根据消费总金额，判断是否升级为合格会员
            //添加每日新增业绩
            Jjjs::sj_and_save_xzyj($user_id, $amount, $from_info);
            */
        }
        
        
        if($result1 && $result2)
        {
            //提交事务
            $model->query("commit");
            $info = array('status'=>'success','msg'=>'操作成功');
            echo JSON::encode($info);
            die;
        }
        else
        {
            //回滚事务
            $model->query("rollback");
            $info = array('status'=>'fail','msg'=>'操作失败');
            echo JSON::encode($info);
            die;
        }
    }
    
    
    
    
    
    
    
    public function gq_do()
    {
        //转换类型
        $zh_type  = intval( Filter::int(Req::args('zh_type')) );
        //$zh_get = Filter::txt(Req::args('zh_get'));
        $amount   = floatval( Filter::txt(Req::args('amount')) );
        $pass2    = Filter::txt(Req::args('pass2'));
        $model    = new Model();
        $user_id  = intval(Req::args('user_id'));
        $user_obj = Common::get_user_obj($user_id);
    
        if($zh_type === 0 && !Common::is_not_allow_do_by_time())
        {
            $info = array('status'=>'fail','msg'=>'此时不允许执行该操作');
            echo JSON::encode($info);
            die;
        }
    
        if(!Common::check_pass2($user_id, $pass2))
        {
            $info = array('status'=>'fail','msg'=>'交易密码不正确');
            echo JSON::encode($info);
            die;
        }
        
    
        
        if($amount < 1)
        {
            $info = array('status'=>'fail','msg'=>'兑换金额最低不能小于1');
            echo JSON::encode($info);
            die;
        }
       
        //兑换类型
        switch($zh_type)
        {
            case 0:
                $zh_from_account_type = 'balance';
                $zh_to_account_type   = 'voucher';
                $desc                 = "账户余额 购买 消费券";
                break;
            case 1:
                $zh_from_account_type = 'currency_point';
                $zh_to_account_type   = 'voucher';
                $desc                 = "通用积分 购买 消费券";
                break;
                /*
            case 2:
                $zh_from_account_type = 'currency_point';
                $zh_to_account_type   = 'ok_xfjf';
                $desc                 = '通用积分 兑换 可用积分';
                break;
            case 3:
                $zh_from_account_type = 'ok_xfjf';
                $zh_to_account_type   = 'currency_point';
                $desc                 = '可用积分 兑换 通用积分';
                break;
                */
        }
    
        /**
         * 如果账户余额不足
         */
        $ye = $user_obj[$zh_from_account_type];
        if($amount > $ye)
        {
            $info = array('status'=>'fail','msg'=>'余额不足');
            echo JSON::encode($info);
            die;
        }
    
        $from_amount = $amount;
        $to_amount   = $amount;
        
    
        $model->query("start transaction");
    
        $result1 = $model->table("customer")->data([$zh_from_account_type=>"`$zh_from_account_type`-$from_amount",$zh_to_account_type=>"`$zh_to_account_type`+$to_amount"])->where("user_id=$user_id")->update();
        $data['user_id'] = $user_id;
    
        $data['zh_lx']    = $zh_type;
        $data['zh_desc']  = $desc;
        //兑换金额
        $data['zh_money'] = $from_amount;
        //实际到帐金额
        $data['real_money'] = $to_amount;
        $data['zh_time']  = date('Y-m-d H:i:s');
        $result2 = $model->table("zh")->data($data)->insert();
    
        if($zh_type === 0)
        {
            $from_info = $user_obj['name'].$desc;
        }
        elseif($zh_type === 1)
        {
            $from_info = $user_obj['name'].$desc;
        }
        //产生各种奖金  账户余额兑换消费券的时候财产生各种奖金，同时升级，同时保存每日新增业绩
        //账户余额兑换消费券  和通用积分兑换消费券  这2个操作都产生奖金
        if($zh_type === 0 || $zh_type === 1)
        {
            //产生奖金
            Jjjs::exec_all_jj($user_id, $amount, $from_info);
            //根据消费总金额，判断是否升级为合格会员
            //添加每日新增业绩
            Jjjs::sj_and_save_xzyj($user_id, $amount, $from_info);
        }
    
    
        if($result1 && $result2)
        {
            //提交事务
            $model->query("commit");
            $info = array('status'=>'success','msg'=>'操作成功');
            echo JSON::encode($info);
            die;
        }
        else
        {
            //回滚事务
            $model->query("rollback");
            $info = array('status'=>'fail','msg'=>'操作失败');
            echo JSON::encode($info);
            die;
        }
    }
    
    
    
    
    
    
    
    
    
    
    /**
     * 在自己的个人中心进行注册会员
     */
    public function reg_user()
    {
        $this->redirect();
    }
    
    public function sqdl()
    {
        //获得上一次的申请记录
        $user_id = $this->mobile_user['id'];
        
        $model = new Model();
        $list = $model->table("sq_list")->where("user_id=$user_id")->order("sq_id desc")->limit("1")->select();
        
        if(!empty($list))
        {
            $this->assign("sq_obj", $list[0]);
        }
        $this->redirect();
    }
    
    
    
    //申请代理
    //必须是合格会员
    public function agent_add()
    {
        $id       = $this->mobile_user['id'];
        $sq_lx    = intval( Filter::int(Req::args('lx')) );
        $user_obj = Common::get_user_obj($id);
        $u_lx     = intval($user_obj['u_lx']);
        //直推人数
        $u_tjrs   = $user_obj['u_tjrs'];
        $tuan_yj  = $user_obj['tuan_yj'];
        
        $glj1 = Common::getConfigJjsetValue("jjset_glj1");//服务中心的直推人数
        $glj2 = Common::getConfigJjsetValue("jjset_glj2");//服务中心的团队业绩
        $glj3 = Common::getConfigJjsetValue("jjset_glj3");//分公司的直推人数
    
        $result = false;
    
        $model = new Model();
    
        //判断之前的审核是否通过
        $sq_count = $model->table("sq_list")->where("user_id=$id and is_ok=0")->count();
    
        if($sq_count > 0)
        {
            $info = array('status'=>'fail','msg'=>'您之前提交的申请正在审核中，请不要重复提交！');
            echo JSON::encode($info);
            die;
        }
    
        if($u_lx === 0)
        {
            //如果用户不是合格的会员，则无法提出申请
            if(intval($user_obj['is_hg']) === 0)
            {
                $info = array('status'=>'fail','msg'=>'您的条件不满足，暂时无法申请！');
                echo JSON::encode($info);
                die;
                
            }
    
            if($sq_lx === 1)//申请的是服务中心
            {
                if($u_tjrs>=$glj1 && $tuan_yj>=$glj2)
                {
                    $result = self::save_sq_info($id, $sq_lx);
                }
                else
                {                    
                    $info = array('status'=>'fail','msg'=>'您的条件不满足，暂时无法申请！');
                    echo JSON::encode($info);
                    die;
                }
            }
            elseif($sq_lx === 2)//申请的是分公司
            {
                if($tuan_yj >= $glj3)
                {
                    $result = self::save_sq_info($id, $sq_lx);
                }
                else
                {                    
                    $info = array('status'=>'fail','msg'=>'您的条件不满足，暂时无法申请！');
                    echo JSON::encode($info);
                    die;
                }
            }
        }
        elseif($u_lx === 1)
        {
            if($sq_lx === 1)
            {                
                $info = array('status'=>'fail','msg'=>'您当前的身份已经是服务中心，请不要重复操作！');
                echo JSON::encode($info);
                die;
            }
            elseif($sq_lx === 2)
            {
                if($tuan_yj< $glj3)
                {                    
                    $info = array('status'=>'fail','msg'=>'您的条件不满足，暂时无法申请！');
                    echo JSON::encode($info);
                    die;
                }
                else
                {
                    $result = self::save_sq_info($id, $sq_lx);
                }
            }
        }
        elseif($u_lx === 2)
        {
            $info = array('status'=>'fail','msg'=>'您当前已经是分公司了，请不要重复操作！');
            echo JSON::encode($info);
            die;
            
        }
    
        if($result)
        {
            //$this->redirect("sq_ckordp",false,array('msg'=>array("success","申请成功，等待审核！")));
            
            $info = array('status'=>'success','msg'=>'操作成功，等待审核');
            echo JSON::encode($info);
            die;
        }
        else
        {
            //$this->redirect("sq_ckordp",false,array('msg'=>array("error","操作失败！")));
            
            $info = array('status'=>'fail','msg'=>'操作失败');
            echo JSON::encode($info);
            die;
        }
    }
    
    
    
    
    /**
     * 在交易大厅每天买入可用消费积分
     */
    public function buy_ok_xfjf()
    {
        if( !Common::is_not_allow_do_by_time())
        {
            Common::return_info_msg("fail", "此时不允许执行该操作");
            die;
        }
    
        //买方用户id
        $user_id = $this->mobile_user['id'];
        
        if(empty($this->mobile_user) || intval($user_id) <= 0)
        {
            Common::return_info_msg("fail", "请登录后在进行该操作");
            die;
        }
        
        
        $sell_id = intval(Req::args("sell_id"));
        //购买的数量
        $quantity = intval(Filter::int(Req::args("quantity")));
        //$price    = floatval( Filter::float(Req::args('price')));
        //交易密码
        $pass2    = strval(Filter::text(Req::args('pass2')));
    
        /*
         * 二级密码是否正确
         * 买入数量是否超标
         * 账户余额是否不足
         * 买方用账户余额购买，购买成功后，
         *                           对于卖方来说，直接到账号账户余额(总价格扣除15%的反哺费，同时反哺费加入到每日消费总金额用于加权分红)
         *                           对于买方来说，直接到帐到通用积分账户,同时扣除买方的账户余额金额
         *                           扣除的反哺费保存到新增业绩表中
         * 保存购买记录到transaction_buy表
         * transaction_sell表的对应买家的last_quantity累减
         *
        */
        
        $model = new Model();
        if(!Common::check_pass2($user_id, $pass2))
        {
            Common::return_info_msg("fail", "您输入的交易密码不正确");
            die;
        }
    
        $transaction_sell_obj = $model->table("transaction_sell")->where("id=$sell_id")->find();
        //剩余可购买数量
        $sell_last_quantity   = intval( $transaction_sell_obj['last_quantity'] );
        //单价
        $price                = floatval( $transaction_sell_obj['price'] );
        //卖方用户id
        $seller_id            = intval( $transaction_sell_obj['user_id'] );
    
    
        if($quantity > $sell_last_quantity)
        {
            Common::return_info_msg("fail", "最多可买".$sell_last_quantity);
            die;
        }
    
        if($quantity < 1)
        {
            Common::return_info_msg("fail", "买入数量至少为1");
            die;
        }
        //获得买方对象
        $customer_obj = $model->table("customer")->fields("balance")->where("user_id=$user_id")->find();
    
        //获得买方账户余额
        $balance = floatval( $customer_obj['balance'] );
        //购买需要支付的总金额
        $buy_dz_je = $quantity * $price;
    
        if($balance < $buy_dz_je)
        {
            Common::return_info_msg("fail", "账户余额不足");
            die;
        }
    
        $model->query("start transaction");
    
        //购买成功，买方通用积分累加,账户余额累减
        //比如用270块钱去买300个单价为0.9的通用积分,通用积分到帐的是买的数量,而扣除的是单价*数量，包括买家的到帐金额也是单价*数量
        $res1 = $model->table("customer")->data(['currency_point'=>"`currency_point`+$quantity",'balance'=>"`balance`-$buy_dz_je"])->where("user_id=$user_id")->update();
    
        //购买成功，卖方到帐到账户余额，实际到帐金额 = 总金额 - 反哺费
        $fbf_bili = Common::getConfigJjsetValue("jjset_fbf")/100;
    
        //反哺费
        $fbf_je = $buy_dz_je * $fbf_bili;
    
        //计算出对于卖家来说最终的到帐金额
        $sell_dz_je = $buy_dz_je * (1 - $fbf_bili);
    
        if($sell_dz_je > 0)
        {
            //卖家直接到帐到 账户余额
            $res2 = $model->table("customer")->data(['balance'=>"`balance`+$sell_dz_je"])->where("user_id=$seller_id")->update();
    
        }
    
    
        //保存交易记录
        $data['sell_id']     = $sell_id;
        $data['seller_id']   = $seller_id;
        $data['user_id']     = $user_id;
        $data['price']       = $price;
        $data['quantity']    = $quantity;
        $data['fbf_je']      = $fbf_je;
        //买家到帐的是数量
        $data['buy_dz_je']   = $quantity;
        $data['sell_dz_je']  = $sell_dz_je;
        $data['create_time'] = date('Y-m-d H:i:s');
    
        $res3 = $model->table("transaction_buy")->data( $data )->insert();
    
        if($quantity === intval($sell_last_quantity))
        {
            $da = ['last_quantity'=>"`last_quantity`-$quantity",'status'=>1];
        }
        else
        {
            $da = ['last_quantity'=>"`last_quantity`-$quantity"];
        }
        //transaction_sell表中剩余可购买数量累减
        $res4 = $model->table("transaction_sell")->data( $da )->where("id=$sell_id")->update();
    
        //奖扣除的反哺费保存到新增业绩表中
        $res5 = $model->table("every_day_xzyj")->data(['user_id'=>$seller_id,'xzyj'=>$fbf_je,'status'=>1,'no'=>$res3,'create_time'=>date('Y-m-d H:i:s')])->insert();
    
        if($res1 && $res2 && $res3 && $res4 && $res5)
        {
            $model->query("commit");
            Common::return_info_msg("success", '操作成功');
            die;
        }
        else
        {
            $model->query("rollback");
            Common::return_info_msg("fail", '操作失败');
            die;
        }
    }
    
    
    /**
     * 在交易大厅每天卖出可用消费积分
     */
    public function sell_ok_xfjf()
    {
        /*
        if(empty($ths->mobile_user))
        {
            Common::return_info_msg("fail", "请登录后在进行该操作");
            die;
        }
        */
        $user_id = $this->mobile_user['id'];
        if(empty($this->mobile_user) || intval($user_id) <= 0)
        {
            Common::return_info_msg("fail", "请登录后在进行该操作");
            die;
        }
        //卖出数量是否为100的倍数
        //卖出单价是否》=0.9
        //交易密码是否正确
        //账户余额是否不足
        //扣除账户金额
        //保存相关数据到交易表中
        //返回结果
        $quantity = intval(Filter::int(Req::args("quantity")));
        $price    = floatval( Filter::float(Req::args('price')));
        $pass2    = strval(Filter::text(Req::args('pass2')));
        $desc     = strval(Filter::text(Req::args('desc')));
    
        if($quantity >= 100 && $quantity % 100 ==0)
        {
        }
        else
        {
            Common::return_info_msg("fail", "卖出数量必须为100的倍数");
            die;
        }
    
        //从配置文件中找到可用积分的最低单价
        $ok_xfjf_price1 = floatval( Common::getConfigJjsetValue("jjset_ok_xfjf_price1") );
        $ok_xfjf_price2 = floatval( Common::getConfigJjsetValue("jjset_ok_xfjf_price2") );
        if( $price < $ok_xfjf_price1  || $price > $ok_xfjf_price2)
        {
            Common::return_info_msg("fail", "卖出价格范围为$ok_xfjf_price1 - $ok_xfjf_price2");
            die;
        }
    
        if(!Common::check_pass2($user_id, $pass2))
        {
            Common::return_info_msg("fail", "您输入的交易密码不正确");
            die;
        }
        $model        = new Model();
        $customer_obj = $model->table("customer")->fields("ok_xfjf")->where("user_id=$user_id")->find();
        //可用积分账户余额
        $ok_xfjf = $customer_obj['ok_xfjf'];
        if($price * $quantity > $ok_xfjf)
        {
            Common::return_info_msg("fail", '可用积分余额不足');
            die;
        }
        $model->query("start transaction");
        $res1 = $model->table("customer")->data(['ok_xfjf'=>"`ok_xfjf`-$quantity"])->where("user_id=$user_id")->update();
        $data['user_id']       = $user_id;  //卖家用户id
        $data['price']         = $price;  //卖出单价
        $data['quantity']      = $quantity;//初始数量
        $data['last_quantity'] = $quantity;//剩余数量
        if(!empty($desc))
        {
            $data['desc']          = $desc;
        }
        $data['create_time'] = date('Y-m-d H:i:s');
        $res2 = $model->table("transaction_sell")->data($data)->insert();
        if($res1 && $res2)
        {
            $model->query("commit");
            Common::return_info_msg("success", '操作成功');
            die;
        }
        else
        {
            $model->query("rollback");
            Common::return_info_msg("fail", '操作失败');
            die;
        }
    
    }
    
    
    
    
    
    /**
     * 个人交易  撤销操作
     */
    public function go_back_sell()
    {
        /**
         * 1. 退还可用积分
         * 2. 删除transaction_sell表对应的记录
         */
    
        $id = intval( Req::args("id") );
        $model = new Model();
        $transaction_sell_obj = $model->table("transaction_sell")->where("id=$id")->find();
        if(!empty($transaction_sell_obj))
        {
            $model->query("start transaction");
            $total_je = $transaction_sell_obj['last_quantity'];
            $res1 = $model->table("customer")->data(['ok_xfjf'=>"`ok_xfjf`+$total_je"])->where("user_id=".$transaction_sell_obj['user_id'])->update();
            $res2 = $model->table("transaction_sell")->where("id=$id")->delete();
            if($res1 && $res2)
            {
                $model->query("commit");
                Common::return_info_msg("success", '操作成功');
                die;
            }
            else
            {
                $model->query("rollback");
                Common::return_info_msg("fail", '操作失败');
                die;
            }
        }
        else
        {
            Common::return_info_msg("fail", '操作失败');
            die;
        }
    }
    
    
    public function news_info()
    {
        $id = Req::args("id");
        $model = new Model();
        $news_obj = $model->table("article")->where("id=$id")->find();
        $this->assign("news_obj", $news_obj);
        $this->redirect();
    }
    
    public function info_save()
    {
        $data['real_name'] = Filter::text(Req::args('real_name'));
        $user_id           = $this->mobile_user['id'];
        $data['bank']      = Filter::text(Req::args("bank"));
        $data['bank_kh']   = Filter::text(Req::args("bank_kh"));
        
        $model = new Model();
        $res = $model->table("customer")->data($data)->where("user_id=$user_id")->update();
        if($res)
        {
            $info = array('status'=>'success','msg'=>'操作成功！');
        }
        else
        {
            $info = array('status'=>'fail','msg'=>'操作失败！');
        }
        echo Common::_toJSON($info);
    }
    
    
    /**
     * 删除订单
     */
    public function del_order()
    {
        $order_id = intval(Req::args('order_id'));
        
        
        
        $model    = new Model();
        
        $model->query("start transaction");
        
        $order_obj = Common::get_order_obj_by_id($order_id);
        
        //删除订单信息
        $flag = $model->table("order")->where("id=$order_id")->delete();
        
        //删除订单商品信息
        $flag2 = $model->table("order_goods")->where("order_id=$order_id")->delete();
        
        //记录操作日志
        $order_nos = $order_obj['order_no'];
        
        $user_obj = Common::get_user_obj($order_obj['user_id']);
        
//         $info = array('status'=>'fail','msg'=>$flag."-".$flag2);
//         echo Common::_toJSON($info);
//         die;
        
        if($flag && $flag2)
        {
            Log::op($user_obj['name'],"删除订单",$user_obj['name'].":删除了订单 ".$order_nos);
            $model->query("commit");
            /*
            $msg = array('success','成功删除了订单：'.$order_nos);
            $this->redirect("order_list",false,array('msg'=>$msg));
            */
            $info = array('status'=>'success','msg'=>'操作成功！');
        }
        else
        {
            $model->query("rollback");
            $info = array('status'=>'fail','msg'=>'操作失败！');
        }
        
        echo Common::_toJSON($info);
    }
    
    
    
}

?>